Understanding callback was one of the toughest tasks I had done when I first started working with JavaScript. But gradually it got easier and now it seems like a piece of cake. In this blog, I would try to explain you about callback in the easiest way possible.
Callback is a function which executes only after the execution of the previous function. Little complicated and confusing right? No ! It’s not. Just go through the examples and you will get to know how easy it was. If you want to run the example press FN + F12 in your browser and paste the code in console.
JavaScript Function
First of all let’s see the example of simple JavaScript function. Here, We have two functions girl() and guy(). The condition is that we want to execute guy() only after execution of girl(). Let’s see what we get in the output.
function girl(){ console.log("Hey ! I am Girl and I am ready for the party !!"); } function guy(){ console.log("I am guy and I am leaving for the party"); } girl();guy();
Output: Hey ! I am Girl and I am ready for the party !! I am guy and I am leaving for the party
It worked as we wanted. The reason is because girl() haven’t taken much more time to execute but what if we increase execution time of girl()? Let’s find out in the next example.
Asynchronous Javascript
As we all know JavaScript is asynchronous. Which means if girl() takes time to execute guy() will execute first. Let’s test it by increasing execution time of girl(). I have added setTimeout method. Now girl() will take 3 seconds to execute.
function girl(){ setTimeout(function(){ console.log("Hey ! I am Girl and I am ready for the party !!"); }, 3000); } function guy(){ console.log("I am Guy. I am leaving for the party"); } girl();guy();
Output: I am Guy. I am leaving for the party Hey ! I am Girl and I am ready for the party !!
So the result is little different this time. guy() executed first but we don’t want that so what should we do now ? Let’s find out the solution in the next example.
Understanding Callback
Now to solve this issue we have a savior CALLBACK. What callback will do is it will execute guy() only after girl() executes. Here we are passing guy() as argument and calling it inside girl() as callback. Try this out and find out the output.
function girl(callback){ setTimeout(function(){ console.log("Hey ! I am Girl and I am ready for the party !!"); callback() }, 3000); } girl(function guy(){ console.log("I am Guy. I am leaving for the party"); });
Output: Hey ! I am Girl and I am ready for the party !! I am Guy. I am leaving for the party
The result shows that guy() executed after girl(). Isn’t it it simple ? If you have any doubts please share it with me I will try to fix that. If you enjoyed this post, I’d be very grateful if you’d share your feedback in the comment section.
If you are a javascript developer and want to learn basics of web scraping read my another post on webscrapting
Ajay Jordar..