Task Queue: Macrotasks

Med

The Task Queue (also called Macrotask Queue or Callback Queue) holds callbacks from Web APIs that are ready to execute. When a Web API operation completes (like a timer finishing), its callback is placed in the task queue. The event loop moves one task from this queue to the call stack when the stack is empty.

Interactive Visualization

Macrotask Queue
setTimeout
third0ms
setTimeout
second50ms
setTimeout
first100ms
Microtask Checkpoint
(empty)
Checkpoint runs after each macrotask
CodeSync
1setTimeout(() => console.log('first'), 100);
2setTimeout(() => console.log('second'), 50);
3setTimeout(() => console.log('third'), 0);
4
5console.log('sync');
Output
-
All setTimeout calls registered. Callbacks ordered by delay time.
1 / 8
Key Insight: Macrotasks execute ONE at a time, ordered by when their timer expires, not registration order!

Key Points

  • Macrotasks: setTimeout, setInterval, I/O, UI rendering
  • Callbacks queue here when Web APIs complete
  • Event loop runs ONE macrotask per iteration
  • Macrotasks yield between each other (browser can paint)

Code Examples

Multiple setTimeout Order

setTimeout(() => console.log("1"), 0);
setTimeout(() => console.log("2"), 0);
setTimeout(() => console.log("3"), 0);

console.log("Sync");

// Output: Sync, 1, 2, 3

// All three callbacks queue in order
// Event loop runs one per iteration
// (All with 0ms delay, so queue immediately)

Multiple macrotasks queue in order. Event loop runs one per iteration.

Macrotask Priority

setTimeout(() => console.log("Timeout"), 0);

Promise.resolve().then(() => console.log("Promise"));

console.log("Sync");

// Output: Sync, Promise, Timeout

// Promise queues as MICROTASK
// Microtasks run BEFORE next macrotask
// Even though both have "0 delay"

Macrotasks run after all microtasks, even if queued first.

Common Mistakes

  • Thinking macrotasks run immediately when timer expires
  • Not knowing the difference between macrotasks and microtasks

Interview Tips

  • List macrotask sources: setTimeout, setInterval, I/O, events
  • Know one macrotask per event loop iteration
  • Contrast with microtask queue