Let us understand with the help of another simple application.
Hello World Broadcast
Till now all the code we saw ran instantly. But if a situation arises where you would need to execute some function after certain delay, they we would have to pause the execution of our program. Let us say we want to display a message every second. Then what you would need to do is to pause the program for exactly 1 second before again printing the message.
One way to do this is to run a for loop with a large counter. If your computer executes 1 instruction in a microsecond, then you would need to run a loop having 10,00,000 iteration. But this would be specific to your machine and won’t work as expected in different machines.
Hey Hey…!! what is this “use strict”; on top? and how can you pass a function as an argument to another function??
This same thing is available in your browser’s developer console.
Try the following code in the console.
Here you can see that when you call a(..) , it first prints 12345 and after printing this, the a() function calls the callback function. It is the callback function which prints Hello World to the console.
You can even pass a previously declared function as a callback.
Here we declare two functions a and b which prints “Inside function a” and “Inside function b” respectively. Then we pass the already declared function b() as an argument to a(). Observe that when passing a function as callback, we only need to use the function name.
i.e. use a(b); and not a( b() );
Of course you can pass multiple callback functions.
As you can see, the order in which the callback functions are called in the function a() matters, not the order in which the functions are passed as arguments. Even though we are passing the function b() as the first argument, but callback1() is called before callback() inside the a() function. That is why c() function is called before b().
This concept of callbacks is very heavily used in NodeJS. Its use will be demonstrated in the article about Threads in NodeJS.