How does the Event loop work in javascript?
Javascript is a synchronous single-threaded language. All the javascript code is executed inside the call stack. so what is call stack?
The call stack is used to keep track of multiple function calls. It is a part of the javascript engine. It is like a real stack in data structures where data can be pushed and popped and follows the Last In First Out (LIFO) principle.
The main job of this call stack is to execute whatever comes inside it. We can not execute the script after a certain delay in using the call stack because the call stack does not have a timer.
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('code start')
setTimeout((cb)=>{
console.log("callback is executed")
},4000)
console.log("code end")
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,
code start
code end
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
code start
code end
callback is executed