Skip to content
jshacks.dev
Async

Microtasks vs Macrotasks

Learn the difference between microtasks and macrotasks in JavaScript, which APIs create each, the order they run in and how a microtask loop can starve timers.

6 min read
Summarize in AI
Flat illustration of two options weighed side by side, with the JavaScript, npm, TypeScript and Node.js logos.

Two callbacks scheduled in the same line can run in an order that looks backwards, and the reason is a two-level queue. A macrotask is a unit of work the event loop picks up from a queue: a timer, an I/O callback, a click. A microtask is a smaller job that runs right after the current piece of code finishes and before the loop picks up the next macrotask. Promise callbacks are microtasks, and setTimeout callbacks are macrotasks, so Promise.resolve().then(a) always beats setTimeout(b, 0). This post explains the rule on Node.js 24 and in browsers with printed output, lists which APIs belong to which queue, shows the draining behavior that lets microtasks starve everything else and gives a method for predicting any ordering puzzle.

The rule

After each macrotask, the runtime runs every queued microtask, including ones queued while draining, until the microtask queue is empty. Only then does it pick the next macrotask. In a browser, rendering can happen between macrotasks, and after the microtask checkpoint.

JavaScript
console.log("script start");

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

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

queueMicrotask(() => console.log("microtask: queueMicrotask"));

console.log("script end");
Text
script start
script end
microtask: promise
microtask: queueMicrotask
macrotask: timeout

The script itself is the first macrotask. It runs to the end, printing the two synchronous lines. The microtask checkpoint comes next, and both microtasks run in the order they were queued. Then the timer callback, which is a separate macrotask, runs last.

What belongs in each queue

MicrotasksMacrotasks
Promise then, catch and finally callbackssetTimeout and setInterval callbacks
Continuations after awaitI/O callbacks and events (clicks, messages)
queueMicrotask(fn)setImmediate in Node.js
MutationObserver callbacksMessageChannel messages
process.nextTick in Node.js (its own queue, drained first)The main script itself

process.nextTick is a special case on Node.js. Its queue is processed before promise microtasks, and it has its own post, process.nextTick vs queueMicrotask. For everything else in the table, the split is the one that decides ordering.

Draining happens between macrotasks, and inside them

The microtask checkpoint is not only between loop turns. It also runs when the call stack empties inside a macrotask, for example after each event listener in a browser. In Node.js, microtasks run after each callback finishes.

JavaScript
setTimeout(() => {
  console.log("timer 1");
  Promise.resolve().then(() => console.log("microtask in timer 1"));
}, 0);

setTimeout(() => {
  console.log("timer 2");
}, 0);
Text
timer 1
microtask in timer 1
timer 2

In Node.js 11 and later, the microtask queue is drained after each timer callback, not after all of the timers due in that phase. Older versions drained after the whole batch, and printed timer 1, timer 2, then the microtask. If you read old posts that show the other order, that is the reason. In a browser, the rule is the same, as each task ends with a checkpoint.

Microtasks queue more microtasks

The queue drains until empty, and a microtask may add another. They all run before the next macrotask.

JavaScript
let count = 0;

function again() {
  count += 1;
  if (count < 3) queueMicrotask(again);
}

setTimeout(() => console.log("timer, count is", count), 0);
queueMicrotask(again);
Text
timer, count is 3

All three runs of again happened before the timer, even though each one was queued by the previous. The timer saw the final count.

Starvation

The same rule has an ugly consequence. A microtask that keeps queueing itself never lets the queue empty, so timers, I/O and rendering never get a turn.

JavaScript
let runs = 0;

function spin() {
  runs += 1;
  if (runs < 1_000_000) queueMicrotask(spin);
}

setTimeout(() => console.log("timer ran after", runs, "microtasks"), 0);
queueMicrotask(spin);
Text
timer ran after 1000000 microtasks

The loop is bounded here so that the program ends. Remove the bound and the timer never fires, the page never repaints and the process never handles another request. A recursive promise chain that never yields, such as function loop() { return Promise.resolve().then(loop); }, does the same thing. Anything that must wait for the rest of the world, like a polling loop, should use a macrotask, setTimeout or setImmediate, between iterations.

Why await interleaves the way it does

Each await queues the continuation as a microtask once the promise settles, so async functions advance in lockstep with then callbacks.

JavaScript
async function run() {
  console.log("async: 1");
  await null;
  console.log("async: 2");
}

run();

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

console.log("sync");
Text
async: 1
sync
async: 2
then: 1
then: 2

async: 2 came before then: 1 because the await continuation was queued first, during the call to run(), before the then was attached. Both then run in the order of queueing. A second then is queued only after the first finishes, so then: 2 comes last.

A method for predicting order

Use the same four steps on any puzzle.

  1. Run all the synchronous code, top to bottom, and note which callbacks were scheduled in which queue.

  2. When the stack is empty, run microtasks in FIFO order, adding any that they queue to the end, until none remain. On Node.js, process.nextTick callbacks go first.

  3. Take the next macrotask, which is the oldest due one. For timers, that means the one with the earliest expiry time, and for equal times, the first scheduled.

  4. After it finishes, go back to step 2.

Two timers with different delays follow step 3's rule. A setTimeout(a, 10) scheduled before setTimeout(b, 0) still runs second, because b is due earlier.

Where this matters in real code

State updates before rendering. In a browser, work done in microtasks finishes before the next paint, so batching DOM changes in a promise callback avoids a flash of half-updated content. Frameworks use queueMicrotask for this.

Tests that await timers. If a test schedules a timer and a promise and asserts on their order, it is relying on this rule. That is correct and stable, because the order is specified.

Long chains. A thousand-step promise chain runs without yielding to timers or input. If the work is heavy, break it up by awaiting a macrotask, such as await new Promise((r) => setTimeout(r)), every so often.

Debugging an ordering you did not expect

When a log shows callbacks in a surprising order, label every scheduling call with the queue it uses. Write "micro" next to promise callbacks, await continuations and queueMicrotask, and "macro" next to timers, I/O and events. Then replay the program on paper with the four steps above. Nearly every surprise comes from one of three mistakes: counting an await as a macrotask, forgetting that the whole main script is the first macrotask, or forgetting that a promise handler can queue more handlers that also run before the next timer.

Browser developer tools help here. The Performance panel shows each task as a block on the main thread with the microtasks that ran at its end, so you can see a long chain of promise callbacks holding up a paint. In Node.js, --trace-event-categories and the perf_hooks module give a similar view of how long the loop spent in each phase.

Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.