In simple terms, a
callback function is a function passed into another function as an argument which is then invoked inside the outer function to complete some kind of routine or action.
One of the common callback examples is using
addEventListener in your code. For instance, let’s say you want to execute the function callback when the user clicks on the button.
So take a look at this callback example.
In the above example, we passed a
Callbacks works in two different ways – 1) synchronously and 2) asynchronously
In a synchronous way –– code executes one by one as in the same order as it is written. Take a look at a simple example.
Both functions will execute in the same calling order. Their output is:
All looks good!
This is the simple use-case of synchronous programming. There is no waiting time and code executed immediately one by one.
In asynchronous way –– program needs to wait for something to complete.
For example, waiting for server data response, uploading files, etc. are asynchronous operations. These kinds of operations involve some wait time and don’t execute immediately.
In the case of synchronous functions, the program doesn’t wait for operation completion. It will execute immediately with unexpected results.
One of the simple examples of the asynchronous callback is using a
setTimeout function. It takes a function to execute it at a later time.
Let’s take a look at
Let’s call them again and see what happens.
Guess what? They are not going to execute by their calling order due to delays in func1. Hence the output will be like below:
In the above example, we have two functions –
disp(). In the
multiply() function call, there are two number parameters with
As a result, the
multiply() invokes with parameters 10, 2 and the function
disp() , which is the callback. The multiply() prints the multiplication of two numbers and fires the
There is a another way to write the above code with anonymous function.