setTimeout: This function has couple of parameters – first one is the function to be called and second parameter is the number in milliseconds after which the function has to be called. In the above code snippet, we’re declaring a function ‘sayHello’ and we intend the function to be called after 100 milliseconds.
This setTimeout function is not a normal function. This function interacts with the timer feature of its host environment (browser or NodeJS environment). Whenever we call setTimeout function, browser creates a timer with the number of milliseconds passed to the function. Once that time period (100 milliseconds, in our case) is elapsed, browser will pass the function to the callback queue (commonly referred as message queue)
- ‘first statement’ gets printed at the console as a result of console.log statement at line 1.
- Once the 100 milliseconds time is elapsed, browser would send the callback function(‘sayHello’ in this case) to the callback queue.
- Function ‘sayHello’ would be executed and ‘hello’ would get printed in the console.
What would be the output of the below code snippet? The only difference between this code snippet and the earlier code snippet is the value of the second argument passed to the setTimeout function.
In previous code, we passed 100 milliseconds whereas in this code snippet, we pass 0(zero) milliseconds. Think for a moment and answer.
The output would be the same as the previous code snippet printing ‘first statement’ first and then ‘last statement’ and finally printing ‘hello’.
Here is what happens. Statement at line 1 results in printing ‘first statement’ in the console. In the second statement, ‘timer’ is created by the browser which has to be called after 0(zero) milliseconds. As the time period is 0 milliseconds, the function ‘sayHello’ is pushed to the callback queue immediately.
Now, ‘Event loop’ would process the messages in the call back queue, pushing the function ‘sayHello’ on top of call stack and printing ‘hello’ by executing ‘sayHello’ function.