What is the
After reading this article, you’ll be able to answer the following questions easily:
- How does the Event Loop handle work?
Here’s what MDN says about the Event Loop.
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
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
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.