Study guides · Advanced

Process tasks and microtasks

Separate running work, two queues, microtask checkpoints, and rendering opportunities to explain the order of state changes and visible updates.

Ask Logeia about this articleTry the three questionsReview your answers

Updated

On this page
  1. Goal: reason about ordering rather than elapsed delays
  2. Enqueuing work is different from executing its body
  3. A checkpoint includes newly appended microtasks
  4. An empty microtask queue is not a painted frame
  5. Implementation: a nested microtask and a zero-delay timer
  6. Failure: observing state before its scheduled update
  7. Exercise: repair the dependency between update and observation
  8. Ask Logeia about this articleCheck your understanding

Goal: reason about ordering rather than elapsed delays

Synchronous code, queueMicrotask, and setTimeout written next to one another do not execute all their callback bodies in source order. Track when current execution finishes, what enters each queue, and which work can be selected next. The goal is not to memorize a familiar logging puzzle but to predict the next eligible action from explicit state. Function calls, returns, and event listeners are prerequisites. A zero timeout must not be interpreted as an instruction to interrupt the currently running function immediately.

The event-loop and rendering model fixes one task source and represents synchronous actions, tasks, microtasks, and rendering opportunities with explicit operation cards. Playback speed is not model time. Slower animation does not change semantics, and pausing does not leave a real timer advancing behind the scene. The same input therefore recreates the same intermediate states. This deliberate schedule is useful for investigation, but it is not a simulation of every browser task source or every decision about when to render.

Enqueuing work is different from executing its body

Calling queueMicrotask adds work to a queue; it does not immediately run the entire callback before the surrounding code continues. A zero-delay timer also does not interrupt the current call. Timer conditions becoming satisfied, a task becoming eligible, and that task actually being selected are separate events. The model focuses on those queue transitions rather than presenting an exact wall-clock delay. An animation that moves a card into a queue should not already display the callback’s final effects.

Each operation card identifies both its work and its scheduling category. The same label update can occur synchronously, in a microtask, or in a later task, changing what other operations observe. Keep registration order, execution order, and visible rendering order separate. A delayed display should be explained through its actual waiting state, not merely described as asynchronous. This is especially useful when a read of the DOM sees new state while the last painted screen still contains an older value.

A checkpoint includes newly appended microtasks

At prescribed points, including after the currently processed task, the HTML event loop performs a microtask checkpoint. It takes a microtask, runs it, and continues with work that the microtask itself added. It does not process only the queue length that existed at the beginning. In the example, sync is followed by micro-A, then by micro-B added from micro-A, and only later by the timer task.

ObservationTask sideMicrotask sideTrace
Synchronous executionTimer waitingmicro-A waitingsync
Checkpoint step 1Not runmicro-A appends micro-Bsync,micro-A
Checkpoint step 2Not runmicro-B runs; queue emptiessync,micro-A,micro-B
Later taskTimer runsEmptysync,micro-A,micro-B,timer

An empty microtask queue is not a painted frame

Emptying the queue does not by itself guarantee a new displayed image. The event loop has opportunities to update rendering, but one new frame after every task is not its contract. Visibility, timing, and other conditions also matter. The teaching model exposes rendering-opportunity cards and keeps the current DOM separate from the last painted screen. Observe a label that has changed in the DOM while the screen remains old until a chosen rendering opportunity is processed.

Promise reactions are relevant to microtasks, but a queue card is not a complete Promise implementation. Settled and pending promises, chained reactions, and exception propagation have additional semantics. This lesson concentrates on scheduling categories and checkpoint draining. Do not assume that attaching the word Promise to a card implements every resolution procedure or that all promise-related work completed when the card was registered. A restricted model is most useful when its boundary is explicit.

Implementation: a nested microtask and a zero-delay timer

The standard JavaScript program below is a reference example that runs in Node.js. It records sync, enqueues micro-A, and lets micro-A enqueue micro-B. The final timer checks the complete order rather than asserting too early while work is still pending. The output is sync → micro-A → micro-B → timer. This establishes the example’s scheduling relationship; it does not claim that the entire Node.js event loop and the HTML event loop are identical.

Running this code in an environment without rendering cannot measure DOM changes or pixels. Even in a browser, a console message is not itself a timestamp proving when a user saw the update. The model separately supplies rendering opportunities and shows the output trace, DOM state, and last painted screen together. Record ordering checks and rendering observations as different tests. That distinction explains how computation can finish while visible content remains unchanged, without calling a correct DOM operation a failure.

javascript
const trace = ['sync'];
queueMicrotask(() => {
  trace.push('micro-A');
  queueMicrotask(() => trace.push('micro-B'));
});
setTimeout(() => {
  trace.push('timer');
  console.assert(trace.join(',') === 'sync,micro-A,micro-B,timer');
  console.log(trace.join(' → '));
}, 0);

Failure: observing state before its scheduled update

A program can place a label update in a later task but place its observation in a microtask. The observation then sees the older value. Repair the required dependency: combine suitable work synchronously, use the correct continuation, or change the queue category to match the intended order. Adding a large arbitrary delay may appear to fix one trial without expressing a reliable relationship. First write down which operation needs which state, then choose the scheduling structure.

A microtask that continually enqueues another microtask can also prevent a checkpoint from finishing. Later tasks and rendering may be delayed because the queue never empties. The model stops at finite operation and queue limits, but that is an incomplete run rather than success. A plausible partial output before a limit cannot pass a repair task. Empty queues, microtask-only input, and input without later tasks are useful boundaries; the model should compute the operations present rather than inventing work to resemble its default example.

Exercise: repair the dependency between update and observation

In the event-loop repair task, correct an operation sequence that observes a value before its intended update. Predict where each card is enqueued and which queue changes on the next step. Then test a different label value and a nested microtask case. Matching one final string is insufficient: the observation must follow the state change it depends on. Inspect the trace and state at the observation point to establish that relationship.

Remove one rendering opportunity and compare final DOM state with final displayed state. An old screen does not prove that the mutation failed; identify the stage that has not run. Pausing and resuming must retain queues and dirty state, while changing input and rerunning must restore the initial state. Record current work, both queues, the next checkpoint, and the last rendering opportunity on separate lines in your notes. These observations prepare you to examine geometry reads that require rendering-related work before the next displayed frame.

Try the interactive model

Event loop and rendering

Loading demo checkpoint…

Reading and practice are recorded separately in this browser, for each language.

Learn this in order

Build your CS foundations · STEP 20

Choose a learning path