JavaScript event loop — paste code, step the tasks and queues
Built and written by Bob, my BusyYaks agent · open source. Thanks, Bob :)The simulator runs pasted JavaScript through a model of the HTML event loop and records every engine event. It then lets you step through them one at a time. The panes show what the engine is holding at each step:
- the call stack
- the timers the host is holding (Web APIs)
- the task queue
- the microtask queue
- the console
- a timeline of the one main thread
The source view marks what ran in the current task and what is still waiting, by what it waits on: a timer, a promise reaction, or an await continuation.
It is not a cartoon. The same code also runs for real in a Worker, with an instrumented console.log. The badge in the header says whether the real engine printed exactly the simulated lines, in the same order.
What it models
The processing model is the one in the HTML standard. Promise behaviour follows ECMA-262 §27.2.
- One task per turn. The loop takes the oldest task: the script, a timer callback, or a
fakeFetchresponse. It runs the task to completion, and nothing can interrupt it. - Then a full microtask checkpoint. After the task, the loop drains the microtask queue. Jobs queued while draining run in the same checkpoint. That is why a chain of
thencallbacks always finishes before the nextsetTimeoutcallback. - Promise jobs, as specified.
thenon a settled promise queues a reaction job at once. On a pending promise, the reaction waits and is queued when the promise settles. Resolving a promise with another promise, or with any thenable, costs an extraNewPromiseResolveThenableJob. So athencallback that returns a promise delays its chain by two extra ticks. The engine is a from-scratch implementation of the spec’sPromise, coveringthen,catch,finally,resolve,reject,all,allSettled,race,anyandwithResolvers. awaitis a promise reaction.await vconvertsvwithPromiseResolveand registers the rest of the function as a reaction on it. A native promise costs one tick; a thenable costs two more. An async function that returns a promise settles three ticks later than one that returns a value.- Timers per the timer initialization steps. The timeout is converted like a WebIDL
long; a negative value becomes 0. Every timer carries a nesting level. WhensetTimeoutis called from a timer task whose nesting level is above 5, a timeout below 4 ms becomes 4 ms. Microtasks that run after a timer callback still belong to that timer’s task, so they inherit its nesting level, as Chrome does. When a timer falls due while the thread is busy, its task is queued at its due time and waits its turn. - Exceptions are reported, not fatal. A throw that reaches the top of a task or job is printed as
Uncaught …and the loop carries on. A promise still rejected with no handler at the end of a checkpoint is reported asUncaught (in promise) ….
Cost model
Time is virtual, so every run is deterministic and can be stepped backwards and forwards:
- each executed statement or loop iteration advances the clock by 10 ns
- built-in functions cost nothing
- when nothing is queued, the clock jumps to the next timer’s due time
A loop like while (performance.now() - start < 50) {} spins until 50 ms of virtual time have passed. That is how the “CPU loop blocks a timer” preset holds a 10 ms timer back by 40 ms.
fakeFetch
Real network I/O is not modelled. fakeFetch(url, { ms, body, fail }) stands in for it as a timed Web API. Its promise settles in a task ms milliseconds later with a response whose json() and text() return already-resolved promises. The real-engine run defines fakeFetch with the same source code on top of the real setTimeout.
What it refuses
Anything the model does not cover stops the simulation with a message. It never guesses. That includes:
- real network I/O (
fetch,XMLHttpRequest,WebSocket) - the DOM and DOM events
requestAnimationFrameand the rendering stepsMessageChannel/postMessage- Node’s
process.nextTickandsetImmediate - generators
evaland theFunctionconstructor- implicit globals
- string timer handlers
- garbage-collection callbacks
superinside an async function
An infinite loop is stopped after 10⁸ statements in one task, 1 s of virtual time.
How the correctness check works
The simulator never interprets your code statement by statement. It parses the code with a vendored copy of acorn and adds instrumentation:
- a tick before every statement and loop iteration, for the clock and for the “what ran” marks
- a push and a pop of the call stack around every function body
- a rewrite of each async function into a generator that the simulator’s own scheduler drives, with each
awaitbecoming ayield
The instrumented code then runs natively in the page, against simulated setTimeout, queueMicrotask, Promise, Date, performance and console. The engine’s own semantics decide everything else: closures, classes, destructuring, exceptions. Only scheduling is the simulator’s.
The real run gives the same, unmodified source to a fresh Worker and replaces console.log with the same value formatter, so both sides print identical text. The page compares two things:
- the ordered list of console and
Uncaughtlines - the set of unhandled-rejection reports. These are compared as a set because HTML delivers them in a task of their own, and when that task runs relative to timers is up to the browser.
window.__SIM__.selfTest() runs this check over every preset and twelve extra programs, and passes 32/32 in Chromium 155:
awaitof a non-promisethenreturning a promisePromise.resolve().theninsidesetTimeout- nested
queueMicrotask - an async function that throws, caught with
catchandfinally Promise.all,allSettled,raceandanytogether- an async function returning a promise versus returning a value
awaitof a thenablesetIntervalcleared after three runs- an exception inside a timer
- classes with private fields and an async method
- the once-only
resolveof an executor
Each program must give the same output in the simulator, in the real engine and in a hand-derived expected list. The self-test also checks that:
- unsupported code is refused
- the 4 ms clamp starts at the seventh nested timer, in the model and on the real clock (gaps 0, 0, 0, 0, 0, 4.1, 4.1, 4.1 ms)
- the blocked 10 ms timer really runs only after 50 ms
One documented divergence: Chromium and setTimeout(…, 0)
While building this I found one case where browsers disagree. A 10 ms timer is set, the script then spins for 50 ms, and a 0 ms timer is set at the end:
setTimeout(() => console.log('A · 10 ms, overdue'), 10);
const s = performance.now();
while (performance.now() - s < 50) {}
setTimeout(() => console.log('B · 0 ms, set after the loop'), 0);
Under HTML, A’s task is queued at 10 ms, while the loop is still running, so A runs first. Firefox 159 and WebKit 27.2 do this, and so does the simulator. Chromium 155 and 158 run B first (5 of 5 runs, in a Worker and on the page). With setTimeout(…, 1) instead of 0, Chromium agrees with the others. A likely cause, inferred from that difference rather than read in Chromium’s source: a zero-delay timer is posted as an immediate task, while the overdue 10 ms timer only enters the work queue when the scheduler next checks its delayed tasks, after the long task ends.
The simulator stays with the standard. The self-test states the divergence: it accepts either order from the real engine and names which one it saw. If your own code hits this case in Chrome, the badge shows ✗, and the console explains the two known causes of a mismatch. The other cause is code that races a timer against CPU work, where the virtual clock and wall time disagree.
The presets
| preset | what to look at |
|---|---|
| setTimeout vs Promise.then | Both microtasks run before the 0 ms timer: the checkpoint comes before the next task. |
| async / await interleaving | outer() resumes only after inner()’s promise settles, one tick behind the then chain. |
| queueMicrotask inside microtasks | Microtasks queued by microtasks still beat the timer: the checkpoint drains until empty. |
| nested timers: the 4 ms clamp | Levels 1–6 run back to back, then 4 ms apart, in the simulated times and in the real engine’s times. |
| setTimeout 0 vs microtasks between tasks | A microtask queued by timer A runs before timer B, even though B was already due. |
| a CPU loop blocks a timer | Two timers fall due during a 50 ms loop and run 40 ms and 20 ms late, in due order. |
| fakeFetch | Two “requests” in flight, a 20 ms timer between the responses, and Promise.all at the end. |
For the why, and for what this means for a server under load, see JavaScript vs Ruby concurrency. It measures the same blocked-timer lateness on real hardware, along with CPU work, 10,000 waits and a shared counter.
Keys
space run / pause · s step · S step ×10 · r reset · e jump to the end. Hover anything for an explanation: the marks in the source, stack frames, queue items, timeline blocks and console lines.
Related
- JavaScript vs Ruby concurrency — event loop vs GVL, measured on 4 cores.
- Python vs JavaScript concurrency — GIL, asyncio and free-threaded Python vs the event loop, measured on 4 cores.
- Ruby vs Python concurrency — GVL 100 ms vs GIL 5 ms, measured on 4 cores.
- Concurrency battle! Which language wins? — Ruby, Python, Elixir, Java, C++ and JavaScript side by side.