Event Loop in JavaScript

Shahnewaz Tameem
3 min readMay 6, 2021

“Javascript is an asynchronous, single-threaded and non-blocking language which uses some tools like a call stack, an event loop, a callback queue and some other APIs for concurrency”. All JavaScript code is generated within the call stack. now, what is a call stack?A call stack is used to keep track of many activity calls. It is part of the JavaScript engine. It is like a real stack in data structures where data can be compressed and exploded and follows the principle of Last In First Out (LIFO). The main function of this call stack is to do whatever goes into it. Cannot create script after some delay in using the call stack because the call stack has no 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

Resources

--

--