What is Event  Loop in JavaScript?

What is Event Loop in JavaScript?

ยท

2 min read

Table of contents

No heading

No headings in the article.

The event loop is the pushing of events from the event queue or callback queue to the javascript call stack.

It is this concept which makes javascript behave like a multi-threaded programming language although it is single-threaded.

Call Stack: It is a stack which follows LIFO (last in first out).

Web API: Asynchronous tasks like AJAX call or DOM APIs like setTimeout() will be be pushed here.

Callback Queue: It is a queue which follows FIFO(First in first out).

Event Loop: Checks if the call stack is empty and then pushes the event from the callback queue to the call stack.

Let's understand this with a simple example. Why not ๐Ÿ˜.

console.log("Task A")
AJAX("Task B");
console.log("Task C");

Js runtime will first push the "Task A" to the call stack and execute it and pop it out since it is a synchronous event.

And then it will push "Task B" to call stack and since it is an asynchronous task it will hand over this task to Web APIs (browser). Since the call stack is empty at that moment it will push "Task C" to the call stack and execute that event.

Once the "Task B" (asynchronous) task is complete it will then be pushed into the callback queue.

The event loop will keep track of the call stack and callback queue and will push the event from the callback queue to the call stack.

ย