What is An Event Loop in JavaScript? (original) (raw)

Last Updated : 15 Apr, 2025

The event loop is an important concept in JavaScript that enables asynchronous programming by handling tasks efficiently. Since JavaScript is single-threaded, it uses the event loop to manage the execution of multiple tasks without blocking the main thread.

JavaScript `

console.log("Start");

setTimeout(() => { console.log("setTimeout Callback"); }, 0);

Promise.resolve().then(() => { console.log("Promise Resolved"); });

console.log("End");

`

**Output

Start
End
Promise Resolved
setTimeout Callback

**In this example

JavaScript executes code synchronously in a single thread. However, it can handle asynchronous operations such as fetching data from an API, handling user events, or setting timeouts without pausing execution. This is made possible by the event loop.

How the Event Loop Works

The event loop continuously checks whether the call stack is empty and whether there are pending tasks in the callback queue or microtask queue.

Event-Loop-in-JavaScript

What is An Event Loop in JavaScript?

**Phases of the Event Loop

The event loop operates in multiple phases.

Why is the Event Loop Important?

1. Blocking the Main Thread

Heavy computations block the event loop, making the app unresponsive.

JavaScript `

while(true) { console.log('Blocking...') }

`

An infinite while(true) loop continuously runs, blocking the event loop and freezing the browser by preventing any other task from executing.

2. Delayed Execution of setTimeout

setTimeout doesn’t always run exactly after the specified time.

JavaScript `

console.log("Start"); setTimeout(() => console.log("Inside setTimeout"), 1000); for (let i = 0; i < 1e9; i++) {} // Long loop console.log("End");

`

The blocking loop delays setTimeout execution because the Call Stack is busy so, this code will also lead to Time Limit Exceed Error or will freeze the Browser.

3. Priority of Microtasks Over Callbacks

Microtasks run before setTimeout, even if set with 0ms delay.

JavaScript `

setTimeout(() => console.log("setTimeout"), 0); Promise.resolve().then(() => console.log("Promise")); console.log("End");

`

**Explain

The event loop first check's for function in the microtask queue and then in the call back queue always in JavaScript microtask queue is given more priority than the call back queue that's why the functions present in the microtask queue are executed first.

4. Callback Hell

Too many nested callbacks make code unreadable.

JavaScript `

setTimeout(() => { console.log("Step 1"); setTimeout(() => { console.log("Step 2"); setTimeout(() => { console.log("Step 3"); }, 1000); }, 1000); }, 1000);

`

This creates Callback Hell, making it hard to read and maintain. Use Promises or async/await instead.

Screenshot-2025-02-07-085823

Callback Hell

Best Practices for Working with the Event Loop