JS Runtime

Event Loop, Macrotasks, and Microtask Queue

Prevent 60fps frame starvation and Promise-loop freezes—the Event Loop drains the entire Microtask Queue after every single macrotask before painting.

About this page
READ
2 min
Interactive Simulator

Task vs Microtask vs Frame Scheduling

Observe why Promise.then always runs before setTimeout(0) and before Paint.

Call Stack
Microtasks (1)
Render
Task Queue (1)
Step 1 / 4: 1. Macrotask Execution

Synchronous script schedules setTimeout(cb, 0) then Promise.resolve().then(micro).

setTimeout(cb, 0);
Promise.resolve().then(micro);
Internal State / Memory
callStack
[ "script()" ]
microtaskQueue
[ "micro" ]
taskQueue
[ "cb" ]
Task vs Microtask vs Frame Scheduling

Under the Hood#

The browser Event Loop dequeues one macrotask, runs the Call Stack to completion, and drains the entire Microtask Queue (including microtasks queued during the drain) before entering Update the Rendering. Like a tollbooth with an express VIP lane, the next frame waits until the microtask lane is empty.

  1. Task (Macrotask): An event (click, setTimeout, initial script) enters the Call Stack and executes run-to-completion without preemption.
  2. Microtask Checkpoint: Once the Call Stack empties, V8 drains every queued microtask, including new microtasks scheduled during the drain.
  3. Update the Rendering: When a frame is due (16.6 ms at 60 Hz), the engine runs requestAnimationFrame callbacks, then Style, Layout, Paint, and Composite in the Browser Rendering Pipeline.
JS
setTimeout(() => console.log('4: macrotask'), 0);
requestAnimationFrame(() => console.log('3: before paint'));
Promise.resolve().then(() => console.log('2: microtask'));
console.log('1: synchronous call stack');

Problem Genealogy#

  • 1995 (Single-threaded JS): Synchronous execution model driven by timer and DOM event callbacks.
  • 2015 (ES6 Promises): Dedicated priority queue (Microtask Queue) introduced to settle promises before the next render cycle.
  • 2024+ (scheduler.yield()): Explicit API to yield the main thread while retaining higher priority than third-party tasks, fixing the old setTimeout(fn, 0) hack that sent your continuation to the back of the queue.

Production Pitfalls#

  • Render Starvation: A recursive Promise.resolve().then(...) loop prevents the Event Loop from ever reaching the render phase, freezing the tab completely.
  • rAF vs Promise Ordering: Scheduling a DOM read inside .then() runs before requestAnimationFrame (see Debounce, Throttle, and rAF Coalescing) and can trigger Layout Thrashing on unsynchronized styles.

Where this connects

Prerequisites

Next & related

Mechanical Comparisons