DNA⚡ JavaScriptThe JavaScript Event Loop
ðŸĢHatchlingJavaScriptBrowser APIsPerformance

The JavaScript Event Loop

Understanding the event loop is what separates engineers who debug from engineers who architect. Master the execution model that powers every line of JS.

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 Stack

Execution Order

  1. Synchronous code runs first (call stack)
  2. Microtasks run next (Promise.then, queueMicrotask, MutationObserver)
  3. 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 immediately
  • setTimeout — schedules a macrotask
  • Promise.then — schedules a microtask
  • console.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 rendering

This 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 requestAnimationFrame for visual updates synced with the display refresh
  • Use requestIdleCallback for 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.