What is the Event Loop in JavaScript?
JavaScript is a single-threaded language, meaning it executes one task at a time. But how does it handle asynchronous operations like setTimeout
, fetch
, and Promise
without blocking the main thread? The answer lies in the Event Loop.
How the Event Loop Works
The Event Loop is a mechanism that allows JavaScript to perform non-blocking operations by offloading tasks to the browser (or Node.js) APIs and processing them in a loop.
Key Components:
- Call Stack – Tracks function execution (LIFO: Last In, First Out).
- Web APIs – Browser-provided APIs (
setTimeout
, fetch
, DOM events).
- Callback Queue (Task Queue) – Holds asynchronous callbacks.
- Microtask Queue – For
Promise
callbacks and MutationObserver
.
- Event Loop – Continuously checks the call stack and queues.
Event Loop Execution Flow
- Synchronous code runs first, filling the call stack.
- Async tasks (like
setTimeout
) are sent to Web APIs.
- Once Web APIs complete, callbacks move to the Callback Queue (macrotasks) or Microtask Queue (promises).
- The Event Loop checks:
- If the call stack is empty, it processes Microtasks first (higher priority).
- Then, it picks one Macrotask (e.g.,
setTimeout
).
Example: setTimeout vs. Promise
console.log("Start");
setTimeout(() => console.log("Timeout"), 0);
Promise.resolve().then(() => console.log("Promise"));
console.log("End");
Output:
Start
End
Promise
Timeout
Why?
Promise
(microtask) runs before setTimeout
(macrotask).
Why is the Event Loop Important for Interviews?
- Explains asynchronous behavior in JavaScript.
- Helps optimize performance by avoiding blocking operations.
- Key for debugging race conditions and task scheduling.
Conclusion
The Event Loop ensures JavaScript remains non-blocking while handling async operations efficiently. Mastering it helps in writing optimized code and acing interviews.