JS Microtasks vs Macrotasks: A Complete Guide
Understand the difference between JavaScript microtasks and macrotasks. Learn the exact execution order, which APIs use each queue, starvation risks, and how to use queueMicrotask correctly.
The JavaScript event loop has two distinct queues for deferred callbacks: the microtask queue and the macrotask queue (also called the task queue). They differ in priority and timing. Microtasks run after every task and before any rendering. Macrotasks run one per event loop iteration. Knowing which queue an API uses determines exactly when your code runs.
The Two Queues
// Microtask example: Promise.then
Promise.resolve().then(() => console.log("Microtask"));
// Macrotask example: setTimeout
setTimeout(() => console.log("Macrotask"), 0);
console.log("Synchronous");
// Output:
// Synchronous
// Microtask <-- Always before macrotask
// MacrotaskThe rule: microtasks run to completion after the current task finishes, before the next macrotask starts.
Complete API Classification
| API | Queue Type |
|---|---|
Promise.then() / .catch() / .finally() | Microtask |
async/await continuation (after await) | Microtask |
queueMicrotask(fn) | Microtask |
MutationObserver callback | Microtask |
IntersectionObserver callback | Task (rendering step) |
setTimeout(fn, N) | Macrotask |
setInterval(fn, N) | Macrotask |
DOM event handlers (click, keydown, etc.) | Macrotask |
MessageChannel.postMessage | Macrotask |
requestAnimationFrame | Pre-render (between tasks) |
setImmediate (Node.js) | Check phase (after I/O) |
process.nextTick (Node.js) | Before microtasks! |
Execution Order Drill
console.log("1");
setTimeout(() => console.log("2: setTimeout"), 0);
Promise.resolve()
.then(() => {
console.log("3: Promise 1");
return Promise.resolve(); // Wrapping in a resolved promise adds another microtask tick
})
.then(() => console.log("4: Promise 2"));
queueMicrotask(() => console.log("5: queueMicrotask"));
setTimeout(() => console.log("6: setTimeout 2"), 0);
console.log("7");
// Output:
// 1
// 7
// 3: Promise 1 (microtask)
// 5: queueMicrotask (microtask)
// 4: Promise 2 (microtask -- added when Promise 1's then resolved)
// 2: setTimeout (macrotask -- first task)
// 6: setTimeout 2 (macrotask -- second task, next iteration)How Microtasks Drain
After every task (macrotask) completes, the event loop processes all queued microtasks — and any microtasks they add — before moving on:
// Task: synchronous script
console.log("Task start");
Promise.resolve()
.then(() => {
console.log("Microtask 1");
Promise.resolve().then(() => {
console.log("Microtask 1.1 (added during drain)");
Promise.resolve().then(() => {
console.log("Microtask 1.1.1 (nested further)");
});
});
});
Promise.resolve().then(() => console.log("Microtask 2"));
console.log("Task end");
// Output:
// Task start
// Task end
// Microtask 1
// Microtask 2 (parallel microtask, runs after Microtask 1)
// Microtask 1.1 (added by Microtask 1, runs before any macrotask)
// Microtask 1.1.1 (added by Microtask 1.1)
// (only NOW would a setTimeout callback run)The Starvation Problem
Since microtasks drain completely before any macrotask runs, an infinite chain of microtasks starves macrotasks (and rendering):
// DANGEROUS: Infinite microtask chain
function addInfiniteMicrotasks() {
Promise.resolve().then(addInfiniteMicrotasks);
}
addInfiniteMicrotasks();
// setTimeout NEVER fires:
setTimeout(() => console.log("Never"), 0);
// Page never re-renders (if in browser)Compare with infinite macrotasks — each setTimeout still yields to rendering and other tasks:
// NOT dangerous (but still burns CPU)
function scheduleMacrotask() {
setTimeout(scheduleMacrotask, 0);
}
scheduleMacrotask();
// Page CAN re-render between each task iterationqueueMicrotask
queueMicrotask(fn) is a direct way to schedule a microtask without creating a Promise:
// Similar behavior, different APIs:
queueMicrotask(() => console.log("Via queueMicrotask"));
Promise.resolve().then(() => console.log("Via Promise.resolve()"));
// Both run as microtasks in definition order:
// "Via queueMicrotask"
// "Via Promise.resolve()"When to Use queueMicrotask
// Use case: Defer a callback to after current sync code without creating a Promise
class EventEmitter {
constructor() {
this.listeners = new Map();
this._pendingEvents = [];
}
emit(event, data) {
const handlers = this.listeners.get(event) || [];
// Queue all handlers as microtasks
// They run after current sync code but before any macrotask
handlers.forEach((handler) => {
queueMicrotask(() => handler(data));
});
}
on(event, handler) {
if (!this.listeners.has(event)) {
this.listeners.set(event, []);
}
this.listeners.get(event).push(handler);
}
}
const emitter = new EventEmitter();
emitter.on("data", (d) => console.log("Handler:", d));
emitter.emit("data", 42);
console.log("After emit");
// Output:
// After emit
// Handler: 42async/await and Microtasks
Each await in an async function creates exactly one microtask handoff. The code after await is a microtask continuation:
async function a() {
console.log("a start");
await Promise.resolve(); // Yield -- continuation is a microtask
console.log("a after await");
}
async function b() {
console.log("b start");
await Promise.resolve(); // Yield
console.log("b after await");
}
a();
b();
console.log("sync");
// Output:
// a start
// b start
// sync
// a after await (a resumed first, since it awaited first)
// b after awaitMultiple Awaits
async function multi() {
console.log("1");
await null; // One microtask tick
console.log("3");
await null; // Another microtask tick
console.log("5");
}
multi(); // Starts synchronously
console.log("2"); // Sync code runs before async continuations
setTimeout(() => console.log("6 (task)"), 0); // Macrotask
Promise.resolve().then(() => console.log("4 (microtask)"));
// Output: 1, 2, 3, 4, 5, 6
// 1: multi() starts sync
// 2: sync continues
// 3: first await resolves (microtask)
// 4: queueing microtask runs
// 5: second await resolves (microtask)
// 6: setTimeout fires (macrotask)Practical Implication: UI Batching
Because microtasks run before rendering, you can make multiple DOM mutations in microtasks and they all appear in one frame:
// Both mutations happen before the browser repaints
Promise.resolve()
.then(() => {
element.style.opacity = "0";
element.style.transform = "translateY(-10px)";
})
.then(() => {
// Still a microtask -- still before render
element.classList.add("hidden");
});
// Browser renders once after both microtasks finishComparison: Promise vs setTimeout Timing
function timedComparison() {
const results = [];
setTimeout(() => results.push("setTimeout"), 0);
Promise.resolve().then(() => results.push("Promise.then"));
queueMicrotask(() => results.push("queueMicrotask"));
// At this point, synchronous code is done
// Microtask queue will drain first, then setTimeout fires
return new Promise((resolve) => {
setTimeout(() => {
resolve(results);
}, 10);
});
}
timedComparison().then((r) => console.log(r));
// ["Promise.then", "queueMicrotask", "setTimeout"]Rune AI
Key Insights
- Microtasks always run before macrotasks: After any synchronous code or macrotask finishes, ALL microtasks drain before the next macrotask starts
- Promise.then and queueMicrotask are microtasks: They are guaranteed to run before any setTimeout or setInterval callback regardless of timing
- Microtask chains run to completion: Adding new microtasks during the drain phase extends the drain — they all run before any macrotask
- Infinite microtask loops are fatal: An unbreakable chain of Promises blocks macrotasks and rendering until the tab freezes
- async/await is microtask-powered: Each await handoff is one microtask; code after await resumes before any pending macrotask
Frequently Asked Questions
Why do Promise callbacks run before setTimeout even with the same delay?
Can I control which microtasks run first?
What is process.nextTick in Node.js and how does it differ?
Are there situations where a microtask runs after a macrotask?
Should I prefer queueMicrotask or Promise.resolve().then()?
Conclusion
| Feature | Microtask Queue | Macrotask Queue |
|---|---|---|
| APIs | Promise, queueMicrotask, MutationObserver | setTimeout, setInterval, DOM events |
| Priority | Higher (runs before macrotasks) | Lower (runs one per loop iteration) |
| Drain behavior | All microtasks drained before next macrotask | One task per loop iteration |
| Can block rendering | Yes (if infinite chain) | No (rendering happens between iterations) |
| Can cause starvation | Yes (prevents macrotasks from running) | No |
| Main use | Short continuations after async operations | Deferred work, timers, browser events |
Microtasks and macrotasks are two queues in the event loop with different priorities. Microtasks (Promises, queueMicrotask) drain completely after every task before any macrotask runs. Macrotasks (setTimeout, setInterval, DOM events) run one at a time per loop iteration. Understanding this order is fundamental to writing correct async JavaScript. |
More in this topic
OffscreenCanvas API in JS for UI Performance
Master the OffscreenCanvas API to offload rendering from the main thread. Covers worker-based 2D and WebGL rendering, animation loops inside workers, bitmap transfer, double buffering, chart rendering pipelines, image processing, and performance measurement strategies.
Advanced Web Workers for High Performance JS
Master Web Workers for truly parallel JavaScript execution. Covers dedicated and shared workers, structured cloning, transferable objects, SharedArrayBuffer with Atomics, worker pools, task scheduling, Comlink RPC patterns, module workers, and performance profiling strategies.
JavaScript Macros and Abstract Code Generation
Master JavaScript code generation techniques for compile-time and runtime metaprogramming. Covers AST manipulation, Babel plugin authorship, tagged template literals as macros, code generation pipelines, source-to-source transformation, compile-time evaluation, and safe eval alternatives.