JavaScriptMedium
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 afterawait,queueMicrotask,MutationObserver. In Node,process.nextTickruns even before promise microtasks.
Ordering rules
- Run one macrotask (the initial script is the first one).
- Run every microtask in the queue. Microtasks queued while draining are also run in the same pass.
- Render if needed (browsers).
- 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
setTimeoutinstead 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,MessageChannelor the newerscheduler.yield()(where supported). APromise.resolve()does not yield to rendering.
Code example
js
1const order = [];23setTimeout(() => order.push("macrotask: setTimeout"), 0);45Promise.resolve().then(() => {6 order.push("microtask 1");7 // queued during the microtask drain -> still runs before the timeout8 queueMicrotask(() => order.push("microtask 3 (queued by microtask 1)"));9});10queueMicrotask(() => order.push("microtask 2"));1112order.push("sync code");1314setTimeout(() => {15 console.log(order.join("\n"));16 // sync code17 // microtask 118 // microtask 219 // microtask 3 (queued by microtask 1)20 // macrotask: setTimeout21}, 20);2223// Yielding: chunk long work with setTimeout so other tasks get a turn24async 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 boundary29 }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.