Callbacks In JavaScript
Mrityunjay-Palled
Posted on October 1, 2022
Before discussing callbacks, let's take a look at an example
Output:
secondFunction
firstFunction
In the above example we can see that the secondFunction is executed before the firstFunction even though firstFunction is called before the secondFunction.This happens because of asynchronous nature. Here secondFunction has a timeout of only 1000 milliseconds so it will be executed first and then firstFunction is executed with a timeout of 2000 milliseconds.
If we want to execute secondFunction only after the execution of the firstFunction then we have to use callbacks.
Callbacks: In JavaScript callbacks are nothing but the functions which are passed as an argument to another function, which is then invoked inside the outside function.
Example:
Output:
firstFunction
secondFunction
In the above example we can see that secondFunction is passed as a
callback to the firstFunction which is then invoked inside the firstFunction only after the execution of firstFunction. Now we can see that firstFunction is executed first eventhough it has 2000 milliseconds of timeout.
Benefits Of Callbacks:
Can be used when you want to invoke certain function only after
the execution of another functionCan be used when you are waiting for certain results to arrive.
For example, data coming from an API will take some time, so we
have to wait for the data to perform further operations.
Posted on October 1, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 24, 2024