Study guides · Advanced

Draining microtasks to a checkpoint in Rust

Inspect FIFO checkpoints, callbacks queued during draining, timer ordering, and bounded self-registration.

Ask Logeia about this articleTry the three questionsReview your answers

Updated

On this page
  1. Goal: drain work added during the checkpoint
  2. Timers and microtasks enter different structures
  3. Finish the current function, then drain to empty
  4. Worked trace: script, A, B, timer
  5. Bound unending registration
  6. Runnable Rust: consume callbacks added during draining
  7. Inspect rendering boundaries and incomplete checkpoints
  8. Exercise: draw enqueue and execution orders
  9. Ask Logeia about this articleCheck your understanding

Goal: drain work added during the checkpoint

A microtask queue holds follow-up work processed before the next timer-task selection in this model. Connect queueMicrotask to microtask_checkpoint and distinguish processing the initial count from draining until the queue becomes empty. A callback can enqueue another callback during the drain, so those two implementations are observably different.

The project performs checkpoints after the initial script, timer tasks, and explicit click dispatch. Its subset includes named queueMicrotask callbacks but not Promise, async/await, or network operations. The goal is to understand ordering and bounded execution in Rust before expanding the language with more asynchronous syntax.

Timers and microtasks enter different structures

Both APIs defer functions, but they have different consumption rules. A timer stores a deadline and handle and waits for runNext selection. Here a microtask stores a function name in a VecDeque without a deadline. Treating every microtask as a zero-delay timer in one shared list would lose the checkpoint semantics even if the registration calls look similar.

push_back appends work and pop_front consumes it. If A queues B while C is already waiting, the order is A, C, B. Inserting B immediately after A would incorrectly jump ahead of existing work. Record enqueue and execution times in separate columns, then add one more level of callbacks to test whether the ordering remains FIFO.

Use A and C as the initial queue and let A append B. Before A starts, the queue contains A,C; while A executes, C remains pending; after registration it contains C,B. Those three snapshots distinguish removing an item from invoking it and appending another item. Match every enqueue to exactly one later invocation unless a diagnostic stops the checkpoint. This gives a stronger invariant than comparing only the final output: duplicated or lost callbacks can sometimes be hidden when two functions print the same string.

Finish the current function, then drain to empty

queueMicrotask(a) does not call a at the registration site. The initial script completes before a runs at the checkpoint. If a queues b, b runs in that same checkpoint. The stopping condition is that no item remains, not that the number present at checkpoint entry has been processed.

microtask_checkpoint reuses call_function, so Rust evaluates bindings and DOM operations inside the callback rather than merely printing its name. Inspect queue removal, stack entry, return, and subsequent selection in the frames. Keep task selection separate from checkpoint entry when describing the trace.

Worked trace: script, A, B, timer

The timer has deadline zero, yet the initial script prints script first. Its following checkpoint prints A and then B, which A enqueued. At that point the microtask queue is empty while one timer remains. A single runNext then prints timer. Equating registration order with output order would incorrectly put the timer first.

Compare an input with no operations against one with [{"type":"runNext"}]. A and B already execute in the former because the initial checkpoint does not wait for a clock operation. Isolate the added output in the latter to distinguish the timer callback from microtasks that finished before task selection.

javascript
function later() { console.log("timer"); }
function b() { console.log("B"); }
function a() { console.log("A"); queueMicrotask(b); }
setTimeout(later, 0);
queueMicrotask(a);
console.log("script");
StageOutputPending
Script endsscripttimer / A
Microtask AAtimer / B
Microtask BBtimer
runNexttimernone

Bound unending registration

A microtask that repeatedly queues itself can keep a checkpoint alive while the simultaneous queue size remains one. A pending-count limit alone cannot stop that pattern. This implementation also bounds cumulative registrations and evaluation work and terminates with a diagnostic. Reaching a limit is different from completing a checkpoint and reaching its rendering opportunity.

The current educational limits include thirty-two operations, thirty-two pending callbacks, and one hundred twenty-eight registrations. These numbers are implementation resource contracts, not requirements imposed on every browser by the HTML Standard. Compare one large burst with a one-at-a-time self-registration chain to explain why pending and cumulative counts protect different boundaries.

Runnable Rust: consume callbacks added during draining

This standalone program takes A from VecDeque, appends B during A, and consumes B in the same while-let loop. It then appends the timer output and asserts the sequence. Compile it with rustc. The program isolates a queue contract; it does not replace tests of JavaScript parsing, diagnostic propagation, or the WASM build.

The small budget illustrates finite iteration. The actual interpreter has its own budgets and diagnostics. Change the loop to process only a saved initial length and observe B remaining. Then put C behind A before the drain begins and verify that B follows C, making the FIFO rule visible rather than relying on terminology.

rust
use std::collections::VecDeque;
fn main() {
    let mut micro = VecDeque::from(['A']);
    let mut output = vec!["script".to_string()];
    let mut budget = 8usize;
    while let Some(callback) = micro.pop_front() {
        assert!(budget > 0); budget -= 1;
        output.push(callback.to_string());
        if callback == 'A' { micro.push_back('B'); }
    }
    assert_eq!(output, ["script", "A", "B"]);
    output.push("timer".into());
    assert_eq!(output, ["script", "A", "B", "timer"]);
    println!("{}", output.join(","));
}

Inspect rendering boundaries and incomplete checkpoints

This implementation records an explicit rendering opportunity after draining the queue. A DOM mutation frame can therefore differ from a later painted result. This is a fixed teaching policy for inspecting before and after states, not a reproduction of physical display refresh timing. The next lesson examines DOM state and paintedDraw in detail.

If evaluation or a resource budget stops the checkpoint early, inspect pending microtasks alongside diagnostics. The last output line alone cannot establish a successful drain. Compare the same rejected input in native and WASM builds and check the stopping point as well as the diagnostic; failures are useful parity cases too.

Exercise: draw enqueue and execution orders

Queue A and C initially, have A queue B, and have C queue D. Before running, write the remaining queue before each callback starts. Register one zero-delay timer and predict how long it stays pending. Include a DOM text mutation in at least one microtask so that ordering affects more than console output.

Design separate counterexamples for a drain restricted to its initial count and an implementation that prepends new work. Repair both rules and check both examples again. Finally try self-registration and explain why a simultaneous-count limit is insufficient, using the actual diagnostic that terminates the bounded interpreter.

Inspect microtasks and paint in Rust

Loading experiment 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