What is the event loop in JavaScript and how does it work?
- Technology:
- JavaScript
Quick answer
The event loop is the mechanism that lets single-threaded JavaScript handle asynchronous work: it runs the call stack to empty, then runs all queued microtasks (promises), then takes the next task (timers, events) from the queue.
Detailed explanation
JavaScript runs one piece of code at a time on the call stack. Async operations such as timers, network requests and DOM events are handled by the browser (or Node.js), which places a callback in a queue when they finish. The event loop waits until the call stack is empty and then moves the next callback onto it.
There are two queues that matter. The macrotask queue holds timers, I/O and UI events. The microtask queue holds promise callbacks and queueMicrotask. After every task, the engine drains the entire microtask queue before taking the next macrotask, which is why a resolved promise runs before a setTimeout of 0.
A long synchronous task blocks everything, including rendering, because nothing else can run until the stack is empty. Splitting heavy work into chunks, using web workers, or yielding to the event loop keeps the page responsive.
Example
console.log("1");
setTimeout(() => console.log("2"), 0);
Promise.resolve().then(() => console.log("3"));
console.log("4");
// Output: 1, 4, 3, 2How to explain it in an interview
JavaScript runs on one call stack. When the stack is empty, the event loop first drains the microtask queue (promise callbacks, queueMicrotask) and then takes the next macrotask, such as a timer or an I/O callback. That is why a resolved promise callback runs before a setTimeout of 0, and why long synchronous work blocks rendering and input.
Key points
- One call stack, many queues
- Microtasks (promises) run before the next macrotask (setTimeout)
- Blocking the stack blocks rendering and input
Common mistakes
- Believing setTimeout(fn, 0) runs immediately. It runs after the current script and all pending microtasks.
- Thinking async code runs in parallel threads. The callbacks still run one at a time on the main thread.
- Creating an endless chain of microtasks, which starves rendering just like a long loop.
Follow-up questions
- Why does setTimeout with 0 delay not run immediately?
- How is the event loop different in Node.js?