Event Loops, Event Tables & Event Queues in JavaScript

July 28, 2019

Ever used the delayed function execution in JavaScript using the setTimeout or setInterval, or even Promises?

But ever wondered how they actually work?
In this article, we are going to discuss how the async events like setTimeoutsetInterval or Promises works in JavaScript.

Understanding the Event Loop

To understand the concept of Event Loops, we first need to understand the following two concepts:
  1. The Event Table
  2. The Event Queue

The Event Table

JavaScript has an event table that keeps tracks of all the events that will be executed asynchronously maybe after some time interval or after the resolution of some API requests.

Event Table is a data structure that stores the list of some delayed events in it.

Whenever you write the statement like:
setTimeout(function() {
    console.log(“This will print after 1 second”);
}, 1000);
It will push the function along with the metadata (in this case, 1000ms is stored) in the Event Table.
After the event occurs (i.e. after 1 second is complete), the Event Tablesends the event to the Event Queue. In the case above, after 1000ms, the Event Table will send the function to be executed to the Event Queue.

Event Queue

An Event Queue is a data structure storing the list of events using the FIFO(First In First Out) policy.

In the example above, the function will be sent to the Event Queue & the function will be picked up by the Event Loop to be executed.

Event Loop

Think of an event loop as a continuously running background task at regular intervals say every millisecond.
After every cycle, the Event Loop checks if there is anything to be executed in the call stack. If the call stack is empty, it checks the Event Queue. If the event queue is also empty, it waits for next event loop iteration.
If it finds some task in the event queue, it picks up & executes the task & then the above sequence will be checked & executed with the next cycle of the event loop.

The Code Playground

With the above concepts understood, what will happen when we execute the following statements in JS sequentially.
setTimeout(()=>{console.log("First")}, 0);
When I executed these statements in the chrome console, I got the output as:

But why Second is before First?

This is because, as we executed the statements, the statements were executed sequentially.
As soon as the first statement executed, the function inside the setTimeoutis stored in the Event Table and the next statement executed which printed the value “Second” in the console.
The Event Table finds that the function needs to be executed after 0 ms, so it immediately sends it to the event queue, from where the event loop takes control of the function in the event queue & executes the function that prints the output “First” in output.
So, we get the output as:

You Might Also Like