Microtask queue

Also known as: microtask

On this page 7

The microtask queue is the queue of short, high-priority callbacks that a JavaScript engine runs immediately after the currently executing script finishes and before the event loop moves on to the next task or to rendering. In browser JavaScript, it holds promise reactions, callbacks scheduled with queueMicrotask() and notifications from MutationObserver.

The queue exists so that work triggered by the current operation can complete as soon as possible but still asynchronously, after the call stack has unwound. Each such callback is called a microtask, and the rule that the queue is fully drained before anything else happens explains much of the ordering behavior of promises and async/await.

How the event loop drains the microtask queue

The HTML Standard defines an event loop that repeatedly takes one task from a task queue, runs it to completion and then performs a microtask checkpoint. During the checkpoint, the browser runs every queued microtask in first-in, first-out order, and microtasks added during the checkpoint run in the same checkpoint. Only when the queue is empty does the loop continue, possibly to rendering.

A checkpoint also occurs whenever the JavaScript call stack becomes empty after a callback returns, for example between two event listeners dispatched for the same user click. This is why a promise resolved inside the first listener settles before the second listener runs when the click comes from a real user, but not when it is triggered by element.click() in script, where the stack is never empty between listeners.

The following sequence summarizes one turn of the loop as specified for windows.

StepWhat happensMicrotask relevance
1. Pick a taskOldest runnable task is taken from a task queueNone yet
2. Run the taskScript, event callback or timer callback executesCan enqueue microtasks
3. Microtask checkpointQueue is drained completelyNested microtasks also run
4. Update renderingAnimation frame callbacks, style, layout, paintCheckpoint after each callback
5. RepeatLoop returns to step 1Queue starts empty
One iteration of the browser event loop

Sources of microtasks

Several platform features enqueue microtasks rather than tasks, because their callbacks must run before the browser does anything visible. The most frequent source is the promise job created when a promise settles and has reactions registered with then, catch, finally or await.

SourceWhen it enqueuesTypical use
Promise reactionsWhen a promise settles with handlers attachedChaining asynchronous results
await continuationWhen the awaited value settlesResuming an async function
queueMicrotask()Immediately on callDeferring work to end of current task
MutationObserverAfter DOM changes are recordedBatching DOM change notifications
APIs that schedule microtasks

Note that requestAnimationFrame callbacks are not microtasks; they run during the rendering step, and a checkpoint follows each of them. Likewise, setTimeout and MessageChannel schedule ordinary tasks (often called macrotasks), which always wait for the microtask queue to empty.

Microtasks compared with tasks

The essential difference is priority and batching. A task represents a discrete unit of work, and the loop runs only one per iteration, while microtasks are all executed together at the next checkpoint. This makes microtasks suitable for completing logically connected work, and tasks suitable for yielding control back to the browser.

PropertyTask (macrotask)Microtask
ExamplessetTimeout, events, network callbacksPromise reactions, queueMicrotask
Executed per iterationOneAll queued, including new ones
Rendering in betweenPossibleNever
Minimum delayClamped timers, often 4 ms when nestedNo delay
Risk when overusedSlow response to inputFrozen page, blocked rendering
Tasks and microtasks side by side

The classic illustration is a script that logs start, schedules a setTimeout with zero delay and resolves a promise. The output order is start, promise callback, timeout callback, because the promise reaction runs at the checkpoint that ends the current script task, while the timer must wait for a later iteration.

Practical use and ordering guarantees

Developers rely on the microtask queue whenever they need code to run after the current synchronous operation but before the next paint. Libraries use queueMicrotask() to batch many state changes into a single update, and frameworks schedule reactive updates as microtasks so that several assignments trigger only one re-render.

  • Use microtasks to keep an API consistently asynchronous, so callbacks never run synchronously in one case and later in another.
  • Use microtasks for batching updates that must be applied before the user sees the next frame.
  • Use tasks instead when long work should be split so the browser can process input and render between chunks.
  • Use requestAnimationFrame when the work is visual and should align with the display refresh.

Within a single checkpoint, ordering is strictly first-in, first-out. Each await adds at least one microtask turn, so two async functions that alternate awaits interleave predictably, a property that tests and debugging tools can depend on.

Pitfalls and common misconceptions

The most serious pitfall is microtask starvation. Because the queue is drained completely, a callback that keeps enqueuing new microtasks prevents the event loop from ever reaching rendering or input handling, and the page freezes as surely as with an infinite synchronous loop.

MisconceptionActual behavior
setTimeout with 0 ms runs before promisesPromise reactions always run first
An async function is fully asynchronousCode before the first await runs synchronously
Microtasks let the browser repaintNo rendering occurs until the queue is empty
Errors in microtasks stop the queueThe error is reported and the next microtask still runs
Misconceptions and the actual behavior

Another subtle issue concerns unhandled promise rejections. The browser reports them only after the checkpoint, when it is clear that no handler was attached, so attaching a catch in a later task can produce a rejection warning followed by a handled event.

In plain words

A web page does its work in turns, like customers at a counter. The microtask queue is a short priority line for follow-up jobs created by the current customer. Before the next customer is served, or the screen is redrawn, every job in that line is finished.

This keeps related steps together and fast. The catch is that the line must eventually end: if jobs keep adding new jobs, nobody else is ever served and the page stops responding.

A real-world example

A front-end team builds a dashboard where a single user action can change ten pieces of state, each of which would normally redraw a chart. Redrawing ten times per click costs about 40 ms of layout and painting, enough to cause visible stutter on mid-range laptops.

The team changes its store so that each state change only marks the chart as dirty and schedules one flush with queueMicrotask() if none is pending. All ten changes complete within the same task, the single microtask then redraws the chart once, and the browser paints the final result in the next frame. Interaction delay drops to under 10 ms, and the chart never shows intermediate, inconsistent values.