What is Event Loop?

What is Event Loop?

In this article, we will learn about the Event Loop and how the JavaScript concurrency model is based on the event loop.

But before we dig deeper into the Event Loop and all that stuff, first let's take a glance at JavaScript and its runtime model.

What is JavaScript?

As we all know since our school days that JavaScript is a single threaded programming language.

Why it is single threaded?

Just a short and simple answer to this question is that the JavaScript runtime model has only one stack (call stack).

A simplified view of JS runtime

As we can see in the above visual that there is only one stack.

JavaScript runtime is responsible for the execution of the JavaScript code.

What is Stack?

  • Stack is the place where functions get called and processed.

  • When a function is called, a new frame is created containing references to the function’s argument and local variables.

  • Stack follows the Last In First Out (LIFO) principle.

  • Stack can process one function at a time. This makes JavaScript synchronous.

  • When a function execution is completed, its frame gets popped out from the stack.

Let’s try to understand it with the help of an example:

Runtime.gif

Frames creation and removal from the stack:

  1. When animal function is called, a new frame is created.

  2. When animal calls canine function, then another frame is created on top of the first one.

  3. When canine calls dog function, then once again, a frame is created on top of all other frames.

  4. When dog returns the string, then the topmost frame is removed from the stack.

  5. After that, when canine returns, the middle frame is removed.

  6. Finally, when animal returns, the last frame is removed.

The arguments and local variables may continue to exist, as they are stored in the heap.

Another thing is Heap, So what is a Heap?

  • Heap is a large unstructured region of memory.

  • Objects are allocated to a heap, as we can see in the above visuals.

  • Data in the heap continues to exist even after the JavaScript code execution has been completed. Heap is cleaned by the JavaScript Garbage Collector, which is a topic for some other day.

Now the million-dollar question is how the JavaScript works asynchronously? After all, it is single-threaded and synchronous in nature.

So, indeed JavaScript works synchronously not asynchronously, but JavaScript runtime model also uses some other components which are not owned by the JavaScript engine itself instead, they are provided by the browser.

These components are Web APIs (a.k.a. browser’s APIs), Message Queue or Callback Queue and the Event Loop. We will see all of them in more detail.

We can see all these components in the following visual.

Runtime

Let's discuss browser provided components:

Web APIs

  • Web APIs are APIs provided by the browsers.

  • Web APIs are not the part of JavaScript engine (like V8).

  • When a Web API is found in the stack, JavaScript pops it out from the stack and move it to the Web APIs execution space in the browser. They do not execute in the stack. Meanwhile, the stack will process all the other functions during the Web API execution.

  • Here is the list of all the available Web APIs, each of them is explained in great detail.

Web APIs

Message Queue or Callback Queue

  • As the name suggest, a message queue is a queue of messages to be processed.

  • A message is an event associated with its handler (callback). This handler is called to handle the message.

  • Message queue follows First In First Out principle (FIFO).

  • When an event occurs, a new message is added to the queue along with the event handler.

Message Queue

Event Loop

  • The event loop is a constantly running process that keeps an eye on both the message queue and the stack.

  • The event loop waits for the stack to be empty and then takes the first message in the queue and send it to the stack for processing.

  • When the processing of the first message is completed and the stack becomes empty once again, then the event loop sends the next message in the queue to the stack and so on.

Event Loop

Let's see an animated demonstration of how all the above-discussed components work together for the following JavaScript program:

function myName() {
  console.log("Hi, I am Oscar");
}

function dog() {
  setTimeout(myName, 2000); // wait at least for 2 sec
}

function canine() {
  dog();
}

function animal() {
  canine();
}

animal();

Browser

Here, one thing that needs your attention is the time specified in the setTimeout API (i.e. 2 sec) is the minimum time to execute the function given to setTimeout, not the exact time because the function may have to wait for the execution of the previous messages in the message queue (if there is any). Only after that, it will be sent to the stack for processing.

So, all the components provided by the browser are behind the asynchronous behaviour of our web applications, not the JavaScript itself.

To increase your comprehension, you can also give a try to this fascinating online tool Loupe created by Philip Roberts.

And that’s it, thanks for your precious time.