JavaScriptMedium
What is the Microtask Queue?
The microtask queue holds short callbacks (promise reactions, code after await, queueMicrotask callbacks and MutationObserver records) that run immediately after the current task finishes and before the browser renders or starts the next task; it is always drained completely.
Properties
- Drained completely: the engine keeps running microtasks until the queue is empty, including microtasks queued by other microtasks.
- Runs before the next task and before rendering: so DOM changes made in microtasks are painted together.
- FIFO order within the queue.
- Also drained after each callback during event dispatch when the stack empties, which is why promise reactions inside a click handler run before the next listener in some cases.
queueMicrotask(fn)
A direct way to schedule a microtask without creating a promise. Useful for:
- Deferring work until the current synchronous code finishes but before anything else (e.g. batching several state changes into one notification).
- Making a function consistently asynchronous.
Dangers
- Starvation: a microtask that always schedules another blocks rendering, input and timers forever. The page freezes even though no single function runs for long.
- Errors thrown in
queueMicrotaskcallbacks are reported as uncaught errors (they do not reject anything).
Microtasks vs setTimeout(fn, 0)
Use a microtask to run "right after this code" and a task (setTimeout, MessageChannel, scheduler.yield()) to yield to the browser so it can render and handle input.
Code example
js
1// Batching: many synchronous updates -> one notification2function createStore(initial) {3 let state = initial;4 let scheduled = false;5 const listeners = new Set();6 return {7 set(patch) {8 state = { ...state, ...patch };9 if (scheduled) return;10 scheduled = true;11 queueMicrotask(() => {12 scheduled = false;13 listeners.forEach((l) => l(state)); // runs once, after all sync updates14 });15 },16 subscribe: (l) => listeners.add(l),17 };18}1920const store = createStore({ a: 0, b: 0 });21let notifications = 0;22store.subscribe((s) => {23 notifications++;24 console.log("render with", s);25});26store.set({ a: 1 });27store.set({ b: 2 });28store.set({ a: 3 });29console.log("synchronous code done, notifications so far:", notifications); // 03031await Promise.resolve(); // let the microtask run32console.log("notifications after microtasks:", notifications); // 13334// Microtasks queued by microtasks run in the same drain, before any timer35const order = [];36setTimeout(() => order.push("timer"), 0);37queueMicrotask(() => {38 order.push("micro 1");39 queueMicrotask(() => order.push("micro 2 (nested)"));40});41await new Promise((r) => setTimeout(r, 5));42console.log(order); // ["micro 1", "micro 2 (nested)", "timer"]
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.