What is An Event Loop in JavaScript?
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
- console.log("Start") executes first.
- setTimeout schedules its callback but does not execute it immediately.
- Promise.resolve().then() is placed in the microtask queue and executes before the callback queue.
- Promise Resolved appears before setTimeout Callback due to microtask priority.
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.
What is An Event Loop in JavaScript?- Call Stack: JavaScript has a call stack where function execution is managed in a Last-In, First-Out (LIFO) order.
- Web APIs (or Background Tasks): These include setTimeout, setInterval, fetch, DOM events, and other non-blocking operations.
- Callback Queue (Task Queue): When an asynchronous operation is completed, its callback is pushed into the task queue.
- Microtask Queue: Promises and other microtasks go into the microtask queue, which is processed before the task queue.
- Event Loop: It continuously checks the call stack and, if empty, moves tasks from the queue to the stack for execution.
Phases of the Event Loop
The event loop operates in multiple phases.
- Timers Phase: Executes callbacks from setTimeout and setInterval.
- I/O Callbacks Phase: Handles I/O operations like file reading, network requests, etc.
- Prepare Phase: Internal phase used by Node.js.
- Poll Phase: Retrieves new I/O events and executes callbacks.
- Check Phase: Executes callbacks from setImmediate.
- Close Callbacks Phase: Executes close event callbacks, e.g., socket.on('close').
- Microtasks Execution: After each phase, the event loop processes the microtask queue before moving to the next phase.
Why is the Event Loop Important?
- Non-blocking Execution: Enables JavaScript to handle multiple tasks efficiently.
- Better Performance: Ensures UI updates and API calls do not freeze the page.
- Optimized Async Handling: Prioritizes microtasks over macrotasks for better responsiveness.
Common Issues Related to the Event Loop
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.
Callback HellBest Practices for Working with the Event Loop
- Use Asynchronous Operations: Avoid blocking the event loop with synchronous file reads or complex calculations.
- Optimize Long-Running Tasks: Use worker threads or child processes for CPU-intensive tasks.
- Use Microtasks Wisely: Since microtasks execute before other queued tasks, excessive usage can delay other operations.
- Leverage setImmediate() for High-Priority Tasks: Unlike setTimeout(fn, 0), setImmediate() executes immediately after the I/O phase.
- Debug Using Performance Tools: Utilize Node.js Performance Hooks and the Chrome DevTools profiler to monitor the event loop behavior.
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read