What is the Event Loop in JavaScript?

February 02, 2020

Event Loop

What is the Event Loop in JavaScript?

More often than not, we don't need to understand this core concept of JavaScript. We can go on our merry way of developing Web Applications and Websites without understanding this. But at times, there are situations (ahem interviews) that might ask you to elaborate on what the Event Loop is. Or simply if you wanted to understand how JavaScript works behind the scenes.

After reading this article, you'll be able to answer the following questions easily:

  1. What happens when we execute JavaScript code?
  2. How does the Event Loop handle work?

Event Loop

Here's what MDN says about the Event Loop.

JavaScript has a concurrency model based on an event loop, which is responsible for executing the code, collecting and processing events, and executing queued sub-tasks. This model is quite different from models in other languages like C and Java.

When I first read this, I was like, there are too many things that I don't know. Let's talk about them one by one. There are four key terms needed to explain the Event Loop:

1. Concurrency Model

According to MIT:

Concurrency means multiple computations are happening at the same time.

Basically, a Concurrency Model is just a defined way of managing multiple tasks (concurrency) inside a Computer.

What's the Concurrency Model that a browser follows?

The browsers Concurrency Model is the Event Loop.

2. Executing the code

The Call Stack is a part of the Event Loop which is responsible for executing the code.

3. Collecting and processing events

An event is also known as a message and it's just a function callback. Any new event that comes in to be executed is pushed into the Callback queue.

4. Executing queued sub-tasks

The Event Loop monitors the Call Stack and the Callback Queue. When the Call Stack is empty, it will take an event (which is just a callback) from the Callback Queue and push it on to the Call Stack. It is only then that the Call Stack is executes the event.

One such iteration is called a tick.


Here's a graphical representation of the Event Loop. Event Loop

The Event Loop is an infinite loop that keeps waiting for a queue (sometimes referred to as the Callback Queue or Event Queue) to be filled with tasks. As and when the callback queue gets filled up with a task, the Event Loop kicks in and removes the task based on FIFO (First In First Out) from the Callback Queue. It is then pushed on to the Call Stack which executes the task.