JavaScript Event loop

Let us understand the JavaScript event loop.

JavaScript Event loop

To understand event loop, first we need to understand how a Call Stack works.

Now that we understand Call Stack, we can move to event loop.

Event loop is an endless loop. Whenever the Call Stack is empty, the event loop pushes the oldest task in the Callback Queue to the Call Stack. So the Callback Queue follows a FIFO approach.

How are tasks added to the Callback Queue?

JavaScript is single threaded language. During the synchronous execution of the code, the functions will simply be getting pushed onto the Call Stack or getting popped out of it.

But let’s consider the scenario for when we execute an asynchronous function. These async functions can be WebAPIs such as fetch or setTimeout among others.

Let’s say, the following line gets executed - setTimeout(callbackFn, 1000).

The setTimeout API is defined in the browser, so the callbackFn function along with the delay is sent to the browser. Now, the Call Stack is empty and free to execute any other code.

When 1000 milliseconds have lapsed, then the browser adds the callbackFn to the Callback Queue.

Now, whenever the Call Stack gets empty, the event loop will push the callbackFn to the Call Stack.


References: