The JavaScript Event Loop
Every senior frontend interview touches the event loop â not because it's a trick question, but because understanding it reveals how you think about asynchronous code at scale.
Why This Matters
If you can't explain why setTimeout(fn, 0) doesn't execute immediately, you'll struggle with:
- Debugging race conditions in complex UIs
- Optimizing rendering performance
- Understanding React's batching behavior
- Building reliable real-time features
The Mental Model
JavaScript is single-threaded but non-blocking. The event loop is the mechanism that makes this possible.
Call Stack â Web APIs â Task Queue â Microtask Queue â Call StackExecution Order
- Synchronous code runs first (call stack)
- Microtasks run next (
Promise.then,queueMicrotask,MutationObserver) - Macrotasks run after (
setTimeout,setInterval,requestAnimationFrame)
The Classic Interview Question
console.log('1');
setTimeout(() => console.log('2'), 0);
Promise.resolve().then(() => console.log('3'));
console.log('4');Output: 1, 4, 3, 2
Why?
console.log('1')â synchronous, runs immediatelysetTimeoutâ schedules a macrotaskPromise.thenâ schedules a microtaskconsole.log('4')â synchronous, runs immediately- Microtask queue drains â
3 - Macrotask queue â
2
Senior-Level Insight
The real interview differentiator: understanding that microtasks can starve macrotasks. An infinite chain of microtasks will block rendering and make setTimeout callbacks wait forever.
function blockForever() {
Promise.resolve().then(blockForever);
}
// This will freeze the browser â no macrotasks, no renderingThis is why React's useTransition and the scheduler exist â they work with the event loop, not against it.
Architect Thinking
When designing systems:
- Use microtasks for critical state updates that must complete before the next render
- Use macrotasks for deferring non-critical work
- Use
requestAnimationFramefor visual updates synced with the display refresh - Use
requestIdleCallbackfor background processing that shouldn't affect perceived performance
The event loop isn't just a JS concept â it's a scheduling framework. Senior engineers treat it as one.