Async Determinism, Fake Timers & Microtask Draining
Fake timers replace Date, setTimeout, and requestAnimationFrame with a virtual priority queue so time-dependent code runs in milliseconds without OS scheduler jitter. Advancing virtual time synchronously still fails when callbacks schedule Promises on the Microtask Queue unless you drain microtasks between ticks.
Fake Timer Heap & Microtask Draining
Trace virtual clock advancement and microtask checkpoint draining across a debounced Promise.
setTimeout inserts a callback at virtual timestamp 200ms without registering an OS timer.
setTimeout(() => fetchResults().then(setState), 200);- virtualNowMs
- 0
- timerHeapSize
- 1
- microtaskQueueSize
- 0
Under the Hood
Calling useFakeTimers() monkey-patches global scheduling APIs on globalThis and maintains an integer now cursor plus a min-heap of pending timer records.
- Clock Virtualization:
setTimeout(fn, 300)inserts{ id, runAt: now + 300, fn }into the heap instead of registering an OS kernel timer. - Synchronous vs Async Advancement:
advanceTimersByTime(300)pops and executes macrotask callbacks synchronously, whereasadvanceTimersByTimeAsync(300)yields anawait Promise.resolve()checkpoint after each timer so microtasks drain in spec order. - VSync Emulation: Mocked requestAnimationFrame schedules callbacks at fixed 16ms virtual offsets rather than waiting for compositor frame deadlines.
vi.useFakeTimers();
let saved = false;
setTimeout(() => Promise.resolve().then(() => { saved = true; }), 200);
// Sync advance runs setTimeout, but Promise.then stays queued until await
await vi.advanceTimersByTimeAsync(200);
expect(saved).toBe(true);Problem Genealogy
- 2012 (Real
sleep(500)in Mocha/Jasmine): Suites accumulated 30s-120s of idle wall-clock wait time and flaked whenever CI runners throttled CPU shares. - 2015 (
lolex/@sinonjs/fake-timers): Eliminated wall-clock waits, but synchronoustick()brokeasync/awaitchains by starving microtask checkpoints. - 2022 (
advanceTimersByTimeAsync): Interleaved macrotask timer pops with microtask queue flushes, matching browser event-loop turn boundaries.
Production Pitfalls
- Deadlocked
waitForPolling: Testing-librarywaitFor()polls withsetTimeoutinternally; enabling fake timers withoutadvanceTimersfreezeswaitFor()until the real test timeout kills the worker. - Unpatched
queueMicrotaskor Worker Clocks: Fake timers only patch globals in the main test realm; Web Workers and native C++fetchtimeouts keep reading real monotonic hardware clocks.
- When not to use Fake Timers: Never enable fake timers for tests awaiting real network sockets, IndexedDB transactions, or multi-frame CSS animations driven by compositor timelines, because virtualizing
setTimeoutstalls internal polling loops and desynchronizes real I/O deadlines.
Connections & Logical Next Steps
Lower-fidelity unit and component layers rely on deterministic fake timers rather than wall-clock waits.
Advancing fake macrotask timers without draining the microtask queue leaves Promise continuations unresolved.
Fake timers mock requestAnimationFrame at fixed 16ms intervals rather than hardware VSync signals.