open atlas
↑ Back to track
JavaScript Engine internals JSE · 07 · 02

Microtasks vs macrotasks: ordering

One macrotask runs per loop turn; the entire microtask queue drains after each macrotask and whenever the JS stack empties. A microtask that enqueues a microtask runs in the same drain — the root of starvation. Plus Node's process.nextTick ordering.

JSE Middle ◷ 13 min
Level
FoundationsJuniorMiddleSenior

A junior asks you to “fix the bug” where this prints 1 4 3 2 instead of 1 2 3 4. There is no bug. The order is the contract: a setTimeout callback waits its turn as a macrotask while a Promise.then jumps ahead as a microtask. If you cannot predict that interleaving cold, you cannot reason about a race in production — and you certainly cannot explain why a tight promise chain just froze the tab.

Two queues, two cadences

The previous lesson fixed who owns what: the host owns the loop and the macrotask queues; the engine owns the microtask queue. This lesson makes the ordering precise, because the two queues drain on completely different cadences.

  • Macrotasks (the spec calls them simply tasks) — exactly one runs per loop turn. Sources: setTimeout/setInterval callbacks, I/O completion callbacks, MessageChannel/postMessage messages, fired DOM events, parsed HTML chunks. After running one, the loop does not immediately run the next macrotask.
  • Microtasks — the entire queue is drained after each macrotask, and again whenever the JavaScript call stack empties. Sources: Promise.then/.catch/.finally reactions, queueMicrotask jobs, await continuations, MutationObserver callbacks.

The asymmetry is the whole point. Macrotasks are rationed — one per turn — so the loop can render and handle input between them. Microtasks are exhaustive — drained to empty — so a coherent unit of async follow-up (a promise chain) completes atomically before anything else happens. The browser overview (browser/01-event-loop/04-microtask-starvation) shows the failure mode at runtime depth; here we tie it to the queue mechanics.

The canonical ordering example

console.log("1: sync start");

setTimeout(() => console.log("4: macrotask (setTimeout)"), 0);

Promise.resolve()
  .then(() => console.log("3a: microtask one"))
  .then(() => console.log("3b: microtask two"));

queueMicrotask(() => console.log("3c: queueMicrotask"));

console.log("2: sync end");
// Output: 1 → 2 → 3a → 3c → 3b → 4

Walk it precisely. The synchronous script is the current macrotask. It runs to completion first: 1, then 2. Along the way it scheduled a macrotask (the setTimeout) and microtasks (the .then and the queueMicrotask). When the script’s stack empties, the engine drains the microtask queue in FIFO order: the first .then (3a) and the queueMicrotask (3c) were enqueued during the sync run, so they go first; 3a’s handler returns, which now settles the chained promise and enqueues 3b — appended to the same drain — so 3b runs before the drain ends. Only when the microtask queue is finally empty does the host pick the next macrotask: 4.

Microtask vs macrotask at a glance
Macrotasks run per loop turn
exactly 1
Microtasks run per checkpoint
all, to empty
Drain order within a queue
FIFO
Render can interleave between
macrotasks only
queueMicrotask vs Promise.then
same queue
Node: process.nextTick vs Promise
nextTick first

Why a microtask that enqueues a microtask is dangerous

Because the microtask checkpoint drains to empty, a microtask that enqueues another microtask before returning is processed in the same drain, not the next one. There is no “next turn” boundary to escape to. Repeat it and the queue never empties:

function spin() {
  Promise.resolve().then(spin); // re-arms inside the same checkpoint
}
spin(); // freezes: the checkpoint never completes, the engine never returns

This is microtask starvation. The host never gets the thread back (the engine is stuck inside PerformMicrotaskCheckpoint from lesson 1), so no macrotask runs, no frame paints, no input is handled. Contrast with a macrotask self-loop — setTimeout(spin, 0) — which re-arms on a host queue, so the engine returns between iterations and the page stays responsive (just busy). The cure for starvation is always to insert a macrotask-level yield into the chain.

Node specifics: process.nextTick and per-phase draining

When you’re reading a Node codebase and process.nextTick fires before your Promise.resolve().then, it’s not a bug or a quirk — it’s an intentional second pre-promise queue. Node complicates the picture with two extra rules. First, process.nextTick callbacks run in a queue that is separate from and drained before the Promise microtask queue. So in Node, process.nextTick always beats Promise.resolve().then. Second, Node’s loop runs in phases (timers → pending callbacks → poll → check → close), and historically Node drained microtasks between phases rather than after every single callback — though since Node 11 it drains microtasks after each individual macrotask callback, bringing it closer to browser semantics.

// In Node:
setTimeout(() => console.log("timeout"), 0);     // timers phase (macrotask)
setImmediate(() => console.log("immediate"));     // check phase (macrotask)
Promise.resolve().then(() => console.log("promise")); // microtask
process.nextTick(() => console.log("nextTick"));  // nextTick queue — first

// Order: nextTick → promise → (timeout|immediate, order between these
// two is not guaranteed from the main module)

The practical senior takeaway: never rely on setTimeout vs setImmediate ordering from the top level, but do rely on process.nextTick running before promise microtasks. And beware: process.nextTick has the same starvation hazard as a microtask loop — a recursive nextTick starves the phase loop just as a recursive .then starves the browser.

Quiz

Inside a `setTimeout` callback you run `Promise.resolve().then(work)` and also schedule another `setTimeout(other, 0)`. In what order do `work` and `other` run?

Quiz

In Node, you schedule `process.nextTick(a)` and `Promise.resolve().then(b)` from the same synchronous block. Which runs first, and why?

Order the steps

Order the output of the canonical example: a sync script that schedules one setTimeout, a two-link .then chain, and one queueMicrotask. Drag the log lines into the order they print.

  1. 1 1: sync start (synchronous, current macrotask)
  2. 2 2: sync end (synchronous, still the same macrotask)
  3. 3 3a: first .then handler (microtask, enqueued during sync)
  4. 4 3c: queueMicrotask (microtask, enqueued during sync)
  5. 5 3b: second .then handler (microtask, enqueued by 3a in the same drain)
  6. 6 4: setTimeout callback (next macrotask, after the queue drains)
Edge cases

await continuations are microtasks too, so they obey the same exhaustive-drain rule. A function that awaits in a loop will interleave its resumptions with every other pending microtask before any macrotask runs. This is why mixing await inside a hot synchronous-feeling loop can quietly defer a render far longer than you expect — the awaits keep the microtask queue non-empty. Lesson 04 makes the await-to-microtask mapping explicit.

Recall before you leave
  1. 01
    State the exact draining rule for macrotasks vs microtasks, and name the sources of each.
  2. 02
    Trace why `1, setTimeout(4), Promise.then(3a).then(3b), queueMicrotask(3c), 2` prints 1 2 3a 3c 3b 4.
  3. 03
    How does Node's ordering differ from the browser, and what is the practical rule?
Recap

Macrotasks and microtasks drain on opposite cadences. Exactly one macrotask runs per loop turn — setTimeout, I/O completions, message events, DOM events — after which the loop can render and handle input. The entire microtask queue, by contrast, drains FIFO to empty after each macrotask and whenever the JS stack empties — Promise reactions, queueMicrotask, await continuations, MutationObserver. Because the drain is exhaustive, a microtask that enqueues another microtask runs in the same drain, not a later turn; repeated, this is microtask starvation, which freezes the page because the engine never finishes the checkpoint and never returns the thread to the host. A macrotask self-loop, by contrast, returns the thread each turn and stays responsive. Node adds a process.nextTick queue drained before the Promise queue (so nextTick wins) and a phase-based loop; since Node 11 microtasks drain after every macrotask callback, close to browser behaviour. The canonical ordering example — 1 2 3a 3c 3b 4 — is the muscle memory every senior needs to reason about async races. Now when you see a tab freeze with no apparent CPU spike, ask first: is something spinning in the microtask queue and never returning the thread to the host?

Practice

Start at the top. Tasks go easiest → hardest: recall a fact, apply it to a case, then a senior-level stretch. Open one, attempt it, then reveal.

recallapplystretch0 of 6 done
Connected lessons
appears again in184

Something unclear?

Ask a question about this lesson. Questions are anonymous and go straight to the author to make the lesson better.

shortcuts expand
search
K
prev piece
k
next piece
j
cycle tier
t
this menu
?
sources3
expand
  1. 01
  2. 02
  3. 03

Trademarks belong to their respective owners. Editorial reference only.