DEV Community

Ranjeet Singh
Ranjeet Singh

Posted on • Originally published at jeetsdev.hashnode.dev

Event loop and Call stack in JavaScript

Event Loop is a confusing enough topic to beginners and is often misunderstood. Here I am going to explain some terms so that you can better understand how things work and what the Event loop is.

Introduction

We hear all the time that JavaScript is a single-threaded programming language which means JavaScript can execute one thing at a time. JavaScript engine executes one line at a time from the top of the file synchronously. So does it means If a function takes a long time to execute, you cannot interact with the web browser during the function’s execution because the page hangs?

The web browser also has other components, not just the JavaScript engine.

When you make a fetch request, call the setTimeout() function, or click a button, the web browser can do these activities concurrently and synchronously.

The setTimeout(), fetch requests, and DOM events are parts of the Web APIs of the web browser. These Web APIs are not part of JavaScript. They are part of Browser.

event loop

Let's understand each part individually so that we can get an idea of how things work asynchronously.

Call Stack and Heap

As we can see here JavaScript engine has a memory heap and a Call Stack. The memory Heap allocates memory for functions and variables and updates the values as per the logic.
The Call Stack is present inside the JavaScript engine and it can execute one thing at a time and all the code gets executed inside this Call Stack. Call Stack follows the Last-In-First-Out (LIFO) sequence.

Web API

The Web APIs are provided by the web browser which gives additional functionality. The Web API calls are added to the Web API container from the Call Stack. So let's suppose we call a set timeout function then
these results don't instantly get inserted into the Call Stack because that would disturb the flow of execution. Rather, it gets added at the end of the Task Queue.

Task Queue

This is a queue that holds all of the tasks which come from the Web API. Task Queue follows the First-In-First-Out (FIFO) sequence.

Event Loop

The Event Loop is essentially an infinite while loop that continuously runs and checks for two things-

  1. If the Call Stack is empty.
  2. If there is any task in Task Queue.

When both these conditions become true, the event loop picks up the first element in the queue and puts it on the call stack for the main thread to execute it.

Thanks for reading! Hope that this makes you feel a bit more comfortable with the event loop!
Feel free to reach out to me if you have any questions on Twitter 😊.

Top comments (0)