What is the difference between Microtasks and Macrotasks?

Macrotasks (tasks) are separate units of work like timers, I/O and events, processed one per event loop turn; microtasks (mainly promise callbacks) run right after the current task finishes, and the whole microtask queue is drained before the next task or render.

Sources

  • Macrotasks: setTimeout, setInterval, setImmediate (Node), I/O callbacks, UI events (click, input), MessageChannel / postMessage.
  • Microtasks: Promise.then/catch/finally, the code after await, queueMicrotask, MutationObserver. In Node, process.nextTick runs even before promise microtasks.

Ordering rules

  1. Run one macrotask (the initial script is the first one).
  2. Run every microtask in the queue. Microtasks queued while draining are also run in the same pass.
  3. Render if needed (browsers).
  4. Next macrotask.

So Promise.resolve().then(a) always runs before setTimeout(b, 0), even if the timeout was scheduled first.

Why it matters

  • Predicting output order in interview puzzles and real bugs.
  • Starvation: a microtask that keeps queueing more microtasks never lets timers, input or rendering happen. A recursive setTimeout instead yields to the browser each time.
  • Batching: frameworks use microtasks to batch updates, so several state changes in one task cause one re-render.
  • Yielding to the UI: to keep the page responsive during long work, break it up with setTimeout, MessageChannel or the newer scheduler.yield() (where supported). A Promise.resolve() does not yield to rendering.

Code example

js
1const order = [];
2
3setTimeout(() => order.push("macrotask: setTimeout"), 0);
4
5Promise.resolve().then(() => {
6 order.push("microtask 1");
7 // queued during the microtask drain -> still runs before the timeout
8 queueMicrotask(() => order.push("microtask 3 (queued by microtask 1)"));
9});
10queueMicrotask(() => order.push("microtask 2"));
11
12order.push("sync code");
13
14setTimeout(() => {
15 console.log(order.join("\n"));
16 // sync code
17 // microtask 1
18 // microtask 2
19 // microtask 3 (queued by microtask 1)
20 // macrotask: setTimeout
21}, 20);
22
23// Yielding: chunk long work with setTimeout so other tasks get a turn
24async function processInChunks(items, chunkSize = 1000) {
25 let done = 0;
26 for (let i = 0; i < items.length; i += chunkSize) {
27 items.slice(i, i + chunkSize).forEach(() => done++);
28 await new Promise((r) => setTimeout(r, 0)); // a real macrotask boundary
29 }
30 return done;
31}
32console.log("processed", await processInChunks(Array(5000).fill(0))); // processed 5000

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app