The above diagram shows that the working of the event loop. The window global object helps to access web API’s inside the call stack. let’s see with an example:
console.log("callback is executed")
when the above code is executed first the global execution context is created and it pushes to the call stack.
After that, the first line of code is executed console.log(“code start”) with the help of console web API’s which is shown in the above diagram
after execution of the first line in the console, you can see the “code start” message.
now in the second line, the setTimeout function starts there execution and in the first argument, we pass the callback function so first it registers a callback function with 4000 milliseconds into web API’s environment and it does not wait 4000 seconds it immediately goes to the next line and executes code so in our case the next line is console.log(“end code”) so it’s print “end code” into browser console and after that, the global execution context is also pop out from the stack.
now our console looks like,
As soon as the timer (4000) milliseconds are expired and if the call stack is empty then, the setTimeout callback function is executed otherwise it waits, but we know that we need to place this callback function inside the call stack.
so the callback function is not directly going to the call stack. It will go to the call stack through the callback queue(also called task queue) which you can see in the above diagram(cb-1 places inside callback queue).
Now finally event loop comes into the picture it continuous monitor the callback queue and call stack, if it found any function inside the callback queue then it checks the call stack, if the call stack is empty then it will put that function into the call stack and the call stack is quickly executed it.
so the final output of the browser console
callback is executed