In the above diagram, we have, Function printHello, which should print Hello; and three more console logs which should print numbers one, two, and three. The order in which these will print are as followed:
- Console.log(“1”) will go to the call stack and then will immediately pop off
- Console.log (“2”) will go to the call stack and then will immediately pop off
- Console.log(“3”) will go to the call stack and then will immediately pop
- printHello function will go to the call stack for a split second and then immediately move to web API, since we have a setTimeout web API call. After it has been executed there, it will go to the callback queue and wait there, until all synchronous calls have been executed.
- Remember all these are happening in a parallel manner.
// print 1
// print 2
// print 3
// "hello world"
While the setTimeout is in the web API, the other console logs will still run in the Call Stack and the setTimeout will wait in the Callback Queue:
- When all the synchronous actions have been executed, and the Call Stack is empty, Callback queue will then pass the setTimeout action to the call stack
- In order to utilize asynchronous calls, we need to make use of Browser API
- A very strict rule is, in order for an asynchronous function to be executed, it must go through Web API and then call-back queue. When the Synchronous codes are executed, the Callback queue will pass its code to the call stack.