Understanding the JavaScript Event Loop
What Is the Event Loop?
The Event Loop is the core mechanism in JavaScript that allows non-blocking, asynchronous behavior — even though JavaScript is single-threaded.
JavaScript can handle multiple tasks simultaneously, such as:
- Timers (setTimeout, setInterval)
- Fetching data from APIs
- Responding to user events (clicks, scrolls, etc.)
Key Components
1. Call Stack – Where function calls are tracked.
2. Web APIs – Browser APIs like DOM, setTimeout, fetch, etc.
3. Callback Queue (Task Queue) – Stores callbacks waiting to run.
4. Microtask Queue – Stores Promise.then, catch, finally, and MutationObserver callbacks.
5. Event Loop – The mechanism that checks if the call stack is clear and pushes tasks from the queues into the stack.
How the Event Loop Works
1. JavaScript runs code in the call stack.
2. If it encounters asynchronous code (like setTimeout), it's sent to Web APIs.
3. After completion, the result (callback) is moved to the queue.
4. The Event Loop checks if the call stack is empty.
5. If it is, it pushes the first task from the microtask queue, then the callback queue.
Example:
console.log("Start");
setTimeout(() => {
console.log("Timeout");
}, 0);
Promise.resolve().then(() => {
console.log("Promise");
});
console.log("End");
Output
End
Promise
Timeout
Why?
- setTimeout is pushed to the callback queue.
- Promise.then goes to the microtask queue.
- Microtasks are executed before callbacks once the stack is clear.
Visual Representation
Call Stack:
|-----------------------|
| console.log("Start") | => Runs
| setTimeout(...) | => Sent to Web API
| Promise.then(...) | => Sent to Microtask Queue
| console.log("End") | => Runs
|-----------------------|
Now Stack is Empty:
1. Microtask Queue: run .then() → "Promise"
2. Callback Queue: run setTimeout → "Timeout"
Key Concepts
Term | Description |
---|---|
Call Stack | Executes functions in LIFO order |
Web APIs | Browser features like timers, fetch, DOM |
Callback Queue | Queues setTimeout, setInterval callbacks |
Microtask Queue | Queues Promises and MutationObservers |
Event Loop | Bridges the queues and the call stack |