Oleg
Chursin
WorkNotesPhotography
One turn of the HTML event loop

What one iteration of a window event loop does: how a task is picked, when microtasks drain, why rendering is a task, and which ordering guarantees actually hold.

Contents · 11 sections

Most of us carry a picture of the event loop that fits on a sticky note. There is a "macrotask queue" and a "microtask queue". The loop takes one macrotask, drains the microtasks, renders a frame, and goes round again roughly every 16 ms. That picture predicts the right answer for the textbook quiz (setTimeout logs after the promise), so it survives. It starts to fail when you need it to tell you something harder, like whether a postMessage beats a setTimeout(0), whether the browser will paint between two tasks you queued back to back, or why a click listener sees a different order of logs when a user clicks than when your test calls element.click().

The HTML Standard's model is more precise than the sticky note, and also less generous. It has several task queues, not one, and they are sets, not queues. It lets the browser choose among them "in an implementation-defined manner". Since January 2024, rendering is no longer a step that runs after each task. It's a task of its own, queued from a parallel loop that waits for a rendering opportunity, and it has to win the same selection as everything else. Microtasks don't wait for the end of a task either: they drain whenever the JavaScript stack becomes empty, which can happen several times inside one task.

This piece walks through one turn of a window event loop as the spec writes it today, then checks the parts that can be checked against Web Platform Tests and against a small probe I ran in three engines. It's the first part of the "How the browser runs your code" series. If you haven't read a spec algorithm closely before, reading a spec algorithm covers the vocabulary ("in parallel", "queue a global task", "implementation-defined") that this one leans on. Every HTML Standard quote below is from the text as it read on 18 October 2026 (its header says "Last Updated 16 October 2026"); ECMAScript quotes are from the ES2027 draft dated 16 October 2026.

Task queues are sets, and the microtask queue isn't one of them

Start with the data structures, because the folk model gets them wrong before any algorithm runs. The HTML Standard's event loop definitions say "An event loop has one or more task queues", and then: "A task queue is a set of tasks." The note that follows explains why. Task queues are sets "because the event loop processing model grabs the first runnable task from the chosen queue, instead of dequeuing the first task." A task is runnable if its document is null or fully active, so a task whose document isn't fully active can sit in a queue while newer tasks behind it run.

The same section says flatly: "The microtask queue is not a task queue." There is one microtask queue per event loop, it really is a queue (first in, first out), and the processing model never picks it in the task-selection step. A microtask is formally a task struct too, created by the queue a microtask algorithm, with its source set to the microtask task source. The spec calls "microtask" "a colloquial way of referring to a task that was created via the queue a microtask algorithm."

Between the two sits the idea that does most of the work: task sources. Every task comes from a task source (the timer task source, the user interaction task source, the posted message task source, and so on). The rule: "For each event loop, every task source must be associated with a specific task queue." Several sources can share one queue. The spec's own example is a browser with one queue for mouse and key events and another for everything else, which "could give keyboard and mouse events preference over other tasks three-quarters of the time, keeping the interface responsive but not starving other task queues." The next sentence is the one guarantee you get out of this arrangement: "the processing model still enforces that the user agent would never process events from any one task source out of order."

So here is the model to carry instead. Each task source feeds exactly one queue. The browser decides how many queues there are and how it chooses between them. Within one source, order is preserved. Across sources, the spec promises nothing.

One turn picks a queue, runs one task and drains microtasks

The processing model is a loop that "must continually run through the following steps for as long as it exists". Here is one turn of a window event loop, paraphrased step by step, with the wording quoted where it carries weight.

  1. Set oldestTask and taskStartTime to null.
  2. If the event loop has a task queue with at least one runnable task:
    1. Let taskQueue be one such queue, "chosen in an implementation-defined manner".
    2. Set taskStartTime to the current time.
    3. Set oldestTask to the first runnable task in taskQueue, and remove it.
    4. If the task has a document, record the task start time for it.
    5. Set the event loop's currently running task to oldestTask.
    6. Perform its steps.
    7. Set the currently running task back to null.
    8. Perform a microtask checkpoint.
  3. Record the end time.
  4. If a task ran, collect the top-level browsing contexts its scripts touched, report long tasks, and record the task end time.
  5. If this is a window event loop with no runnable task left, start an idle period, computing a deadline for requestIdleCallback.
  6. (Worker event loops only) maybe run animation frame callbacks for a dedicated worker, and destroy the loop if it's closing and empty.

That's the whole turn. There is no step that says "update the rendering", and there is no step that says "run all tasks of one kind before another". The microtask checkpoint is step 2.8, inside the branch that ran a task, and it comes after the currently running task has been reset to null. Fig. 1 shows the structure: several queues feeding one selector, a single task running, the microtask queue draining after it, and, off to the side, a parallel loop that drops rendering tasks into one of the queues.

The selection step is where browsers are allowed to differ

Step 2.1 is the single most important phrase in the algorithm for anyone reasoning about order: the queue is "chosen in an implementation-defined manner". The task queue definitions and their three-quarters example make clear that this is deliberate. It's how a browser can prioritize input over timers without the spec having to name a policy. It also means that "a setTimeout(0) runs before a postMessage" is not a property of the platform. It's a property of one engine's queue policy, and it may change between versions without breaking any spec.

The note under step 2.1 adds a wrinkle I'll come back to: "a task queue to which the microtask task source is associated might be chosen in this step." That only happens when a microtask has been moved onto a task queue by spinning the event loop.

Long-task timing and the idle deadline come after the microtasks

Steps 3 to 5 are where the platform's performance APIs hook in. The end time is taken after the microtask checkpoint, so the time attributed to a task includes the microtasks it caused. The same is true for the newer hooks: the processing model calls "record task start time" and "record task end time", and the checkpoint now ends with "record timing info for microtask checkpoint", which is defined in the Long Animation Frames Editor's Draft (dated 15 October 2026). That draft queues a long animation frame entry when a frame, measured from the start of the task that led to it through any rendering update, lasts 50 ms or longer. As of 18 October 2026, webstatus.dev lists long animation frame entries as limited availability, in Chrome and Edge 123 and up only. The metric side of this lives in the Performance track; INP from first principles covers how an interaction's duration is measured up to the next paint.

The idle-period step is more interesting than it looks. When a window event loop has nothing runnable, it computes a deadline for idle callbacks. The deadline starts at the last idle period start time plus 50, and the spec explains the number: "The cap of 50ms in the future is to ensure responsiveness to new user input within the threshold of human perception." It's then pulled earlier by any active timer that expires sooner, and, if any window in the loop has animation frame callbacks or "might have pending rendering updates", by the next expected render: last render opportunity time plus 1000 / refresh rate. So an idle callback's timeRemaining() can never exceed 50 ms, and it shrinks further when a timer is due sooner or when a frame is pending, which includes any requestAnimationFrame callback you've registered. requestIdleCallback() itself is still limited availability on webstatus.dev as of 18 October 2026: Chrome 47, Edge 79 and Firefox 55, with no Safari release listed.

Spinning the event loop is how a microtask becomes a task

Some algorithms in the spec need to wait for something without blocking the loop, while appearing to the caller as if they had paused. The HTML Standard calls this spinning the event loop, and it's best read as a macro rather than a function. Expanded, it does this: remember the currently running task and its source, save a copy of the JavaScript execution context stack and empty it, perform a microtask checkpoint, then, in parallel, wait for the condition and queue a task on the original task source that restores the stack and runs the rest of the original algorithm. Finally it stops the current task, so the event loop (or the microtask checkpoint) can carry on.

The step "Let task be the event loop's currently running task" carries a note: "task could be a microtask." If a microtask spins the loop, the remainder of its work is queued as a task on the microtask task source, onto whichever task queue that source is associated with. That's the case the note under step 2.1 warns about, and the queue a microtask section says it's "the only case in which the source, document, and script evaluation environment settings object set of the microtask are consulted". It's an edge case of spec plumbing, but it's the reason the model gives microtasks a source at all.

Rendering is a task that has to win the selection like any other

For most of the HTML Standard's history, "update the rendering" was a step of the processing model itself: run a task, run microtasks, then maybe render. In January 2024 that changed. whatwg/html pull request #10007, merged on 31 January 2024, is titled "Refactor event-loop processing model to perform rendering as a task". Its description says that instead of updating the rendering after each task, "we wait for rendering opportunities in parallel, and post a special task to update the rendering." It's marked "Not a behavior change", and the rationale is that this "is more in line with existing implementations, and fixes weird cases where e.g. a microtrask queue can run without a current task" (the typo is in the original).

The current text reads like this. A window event loop must "also run the following in parallel, as long as it exists": wait until at least one navigable on this loop "might have a rendering opportunity", set the loop's last render opportunity time, and then, for each navigable that has one, "queue a global task on the rendering task source" to update the rendering. The generic task sources section defines the rendering task source as "used solely to update the rendering".

Two consequences follow directly from the text.

First, the rendering task is selected by step 2.1 like everything else. If your page keeps a queue full of tasks, whether rendering gets a turn between two of them is the browser's choice, made by the same implementation-defined selection. Nothing in the spec says "render after every task" or even "render after every N tasks". The spec also accepts that this "might cause redundant calls to update the rendering", says those calls would have no observable effect, and leaves engines free to queue the task only when one isn't already queued.

Second, when the rendering task does run, it can still decide to do nothing. Its steps filter out documents that are render-blocked, hidden, suppressed for view transitions or without a rendering opportunity. A step labeled "Unnecessary rendering" removes documents where "the user agent believes that updating the rendering of doc's node navigable would have no visible effect" and that have no animation frame callbacks. A further step allows skipping "for other reasons", and the note gives an example that matters for anyone who assumes a frame between two timers: "a user agent might wish to coalesce timer callbacks together, with no intermediate rendering updates." Everything that happens inside the rendering task, from resize and scroll to requestAnimationFrame callbacks, ResizeObserver and paint, is the subject of the next part of this series.

A rendering opportunity is not a 16 ms tick

The other half of the folk model, "rAF runs every 16 ms", is a common case presented as a rule. The spec's definition of a rendering opportunity says a navigable has one "if the user agent is currently able to present the contents of the navigable to the user, accounting for hardware refresh rate constraints and user agent throttling for performance reasons". Then it says, explicitly, "This specification does not mandate any particular model for selecting rendering opportunities."

The numbers in that section are examples, not requirements. At 60 Hz, opportunities occur "at a maximum of every 60th of a second (about 16.7ms)". A browser that can't sustain that "might drop to a more sustainable 30 rendering opportunities per second". For a navigable that isn't visible, the browser "might decide to drop that page to a much slower 4 rendering opportunities per second, or even less", and separately, the rendering task's filter removes hidden documents altogether. So the interval between two requestAnimationFrame callbacks is set by the display, the engine's throttling policy and the page's visibility. On a 120 Hz display it can be about 8 ms. In a background tab it can be never. Code that derives elapsed time by counting frames breaks on all of them; use the timestamp passed to the callback.

Microtask checkpoints happen whenever the stack empties

"Drain microtasks after each macrotask" is true, and it's less than half the story. Step 2.8 of the processing model is one call site of perform a microtask checkpoint. The other important one is in clean up after running script, which runs every time the browser finishes invoking a callback or a script: "If the JavaScript execution context stack is now empty, perform a microtask checkpoint."

That sentence explains a whole family of puzzles. When the browser itself dispatches a click from a real user, it invokes the first listener, the stack empties, the microtasks that listener queued run, and only then is the next listener invoked. When your script calls element.click(), your script is still on the stack while every listener runs, so nothing empties the stack until the end of your script. The spec note right under the cleanup steps says these algorithms "can be invoked reentrantly in an indirect manner, e.g. if a script dispatches an event which has event listeners registered."

click-order.js
const outer = document.querySelector('.outer');
const inner = document.querySelector('.inner');
const log = [];

function onClick() {
  log.push('click');
  // The promise reaction is a microtask.
  Promise.resolve().then(() => log.push('promise'));
}

inner.addEventListener('click', onClick);
outer.addEventListener('click', onClick);

// From script: one stack for both listeners.
inner.click();
queueMicrotask(() => console.log(log.join(' > ')));
// click > click > promise > promise

// From a real user click, the stack empties between listeners:
// click > promise > click > promise

This is the case Jake Archibald's 2015 article Tasks, microtasks, queues and schedules called the "Level 1 bossfight", and Web Platform Tests turned it into task_microtask_ordering.html. The WPT file only tests the synthetic case, and its comment says why: the dispatch is synchronous "and microtasks will not run between event bubbling steps." I checked the trusted case myself. Using Playwright to send a real mouse click to the same markup, all three engines I tested logged click > promise > click > promise, and element.click() logged click > click > promise > promise in all three. The method and versions are in the measurement section below. Fig. 2 shows the two dispatches side by side.

The same rule covers requestAnimationFrame. The run the animation frame callbacks algorithm invokes each callback separately, and each invocation ends with cleanup, so microtasks queued in one rAF callback run before the next rAF callback starts. microtask_after_raf.html tests the narrower claim that promise reactions queued inside a rAF callback run, in order, immediately after it.

The checkpoint drains to empty, then settles rejections and WeakRefs

The checkpoint itself is short, and every step does something you can observe.

  1. If the event loop's "performing a microtask checkpoint" flag is true, return. This is the reentrancy guard. A microtask that runs script ends with cleanup, cleanup calls the checkpoint again, and the flag turns that inner call into a no-op.
  2. Set the flag.
  3. While the microtask queue is not empty, dequeue the oldest microtask, make it the currently running task, run it, and set the currently running task back to null. Microtasks queued during this loop join the same queue and run in the same checkpoint. That's why a promise chain that keeps queuing reactions can starve rendering and input indefinitely: the loop never gets back to selecting a task.
  4. For each environment settings object on this loop, notify about rejected promises. This is where unhandledrejection gets decided.
  5. Clean up IndexedDB transactions.
  6. Perform ClearKeptObjects(). The spec's note: when WeakRef.prototype.deref() returns an object, "that object is kept alive until the next invocation of ClearKeptObjects()". So a WeakRef target you dereferenced stays alive at least until the end of the current checkpoint.
  7. Clear the flag.
  8. Record timing info for the Long Animation Frames API.

Promise jobs are microtasks because HTML says so

ECMAScript doesn't know about microtasks. It defines jobs, and leaves scheduling to the host. The ECMA-262 section on jobs requires that a job runs only when the agent's execution context stack is empty, and that once a job starts, it runs to completion before another starts. Its note is candid about the hosts: "web browsers and Node.js treat Promise-handling Jobs as a higher priority than other work". For promises specifically, HostEnqueuePromiseJob adds one ordering rule: "Jobs must run in the same order as the HostEnqueuePromiseJob invocations that scheduled them."

The HTML Standard's implementation of HostEnqueuePromiseJob is where browser semantics come from: "HTML schedules these operations in the microtask queue." Each promise job is wrapped in a microtask that prepares to run script, runs the job, cleans up, and reports an exception if the job completed abruptly. queueMicrotask() queues a microtask onto the same queue, which is why a .then() registered first runs before a queueMicrotask() registered second. queueMicrotask() is Baseline widely available, per webstatus.dev as of 18 October 2026, and MDN's microtask guide is a decent developer-facing companion to the spec text.

Task sources are the only cross-task ordering contract you get

If ordering within a source is guaranteed and ordering across sources is not, the practical question is which source each API uses. The answer is in each API's algorithm, never in a general rule.

The generic task sources are DOM manipulation, user interaction, networking, navigation and traversal, and rendering. The user interaction one carries a requirement: "Events sent in response to user input (e.g., click events) must be fired using tasks queued with the user interaction task source." Many APIs define their own sources on top of these.

Timers use the timer task source. The timer initialization steps end by queuing "a global task on the timer task source given global to run task", after a wait defined by run steps after a timeout. That algorithm adds an ordering guarantee of its own: before completing, a timer waits until "any invocations of this algorithm that had the same global and orderingIdentifier, that started before this one, and whose milliseconds is less than or equal to this one's, have completed." For setTimeout and setInterval the ordering identifier is the string "setTimeout/setInterval". So two setTimeout(fn, 100) calls on one window fire in call order, and a setTimeout(a, 50) called before setTimeout(b, 100) fires first. The same algorithm also allows the browser to "wait a further implementation-defined length of time", to "pad timeouts as needed to optimize the power usage of the device". The delay you pass is a minimum.

window.postMessage() uses the posted message task source: the message is delivered by queuing a global task on that source given the target window. MessageChannel is different. Each MessagePort has a port message queue, and the spec says: "When a port's port message queue is enabled, the event loop must use it as one of its task sources." Every port is its own task source. Messages on one port arrive in order; messages on two different ports have no specified order relative to each other, and none relative to timers or postMessage.

Put those together and the textbook question "does setTimeout(0) run before postMessage?" has a spec answer: unspecified. Three different task sources, three possibly different queues, one implementation-defined choice. I measured what engines do anyway, below. Don't build on the result.

Hidden pages bend even the timer guarantee

The one timer ordering rule that is written down is under pressure from power-saving work. whatwg/html issue #5925, opened in September 2020 and still open, describes how browsers throttle timers in hidden pages "sometimes in ways that break this ordering guarantee", for example by treating deeply nested timers differently from fresh ones, and asks whether the spec should relax the guarantee to match. Until that's resolved, I'd treat the timer-ordering rule as solid for visible pages and as an open question for hidden ones.

The timer clamp is specified, and engines still count nesting differently

The timer initialization steps contain the rule that gave us the "4 ms minimum" folklore. If the currently running task was itself created by the timer algorithm, the new timer inherits that task's nesting level; otherwise the level is 0. Then: "If timeout is less than 0, then set timeout to 0. If nestingLevel is greater than 5, and timeout is less than 4, then set timeout to 4." The level is incremented and stored on the new task. The spec notes that it counts "nested invocations of this algorithm, not of a particular method", so setInterval and nested setTimeout chains both accumulate it.

Trace it by hand and a chain of setTimeout(tick, 0) started from a non-timer task gets six unclamped timers before the first clamped one. whatwg/html issue #10386, opened in June 2024 and still open as of 18 October 2026, does exactly that trace and reports that none of Chrome, Firefox or Safari matched it at the time: Firefox and Chrome printed four zeros before the first 4 ms delay, and the reporter thought Safari printed five.

I measured this today, with a twist. The spec only inherits nesting when the currently running task is a timer task. During a microtask checkpoint, the checkpoint steps set the currently running task to the microtask. So my reading of the spec is that a setTimeout called from a promise continuation, as in the familiar await sleep(0) loop, starts at nesting level 0 every time and is never clamped.

That reading isn't only mine. WPT has a test for exactly this case, timer-nesting-not-inherited-in-microtask.html: it builds a timer chain past nesting level 5, schedules a 1 ms timer from a queueMicrotask() callback, and asserts it fires in under 4 ms. It arrived in October 2025 as an export from WebKit bug 301008, which says timers created during a microtask checkpoint shouldn't inherit the task's nesting level; that bug is marked REOPENED as of 18 October 2026. On the 17 October 2026 stable runs, the test fails in Chrome 155, Edge 155, Firefox 158 and Safari 27.

yield-loop.js
// Broken: used as a "yield to the browser" in a loop.
// Every engine I tested clamps this after a few
// iterations, even though each setTimeout is called
// from a microtask.
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

async function processAll(items, handle) {
  for (const item of items) {
    handle(item);
    await sleep(0);
  }
}

Here is what I measured, as the median delay at each step of a ten-step chain over 100 repetitions, each repetition started from a fresh MessageChannel task so the first timer is at level 0. The "direct" chain calls setTimeout from inside the timer callback; the "awaited" chain is the loop above.

Engine (build) Direct chain: unclamped steps, then Awaited chain: unclamped steps, then
Chrome 155.0.8059.80 6, then about 5 ms 6, then about 5 ms
Firefox 155.0 (Playwright build) 4, then about 6 ms 4, then about 6 ms
WebKit 27.2 (Playwright build) 10, then 7–8 ms (16-step run) 10, then 7–8 ms (16-step run)

Chrome's direct chain now matches the spec's six. Firefox's matches the four that issue #10386 reported in 2024. The WebKit build I had clamped only after ten levels in a 16-step run, which matches neither the spec nor the issue's guess for Safari; it's a Playwright WebKit build, not Safari 27, so I wouldn't generalize it to Safari without repeating the test there. And all three engines clamp the awaited chain exactly like the direct one, which the spec doesn't ask for and the WPT test above counts as a failure. Fig. 3 lays the three engines against the spec's threshold.

The spec has its own workaround, in a note further down the timers section: to run several milliseconds of work back to back while still yielding, queue the next timer before doing the work, so the clamp overlaps with the work instead of adding to it. That helps a timer-driven loop, but it's still a timer, so it still competes in step 2.1 and the engine may still pad it.

If you need to yield inside a loop, don't depend on the clamp either way. Yield with a task source that has no clamp, and use scheduler.yield() where it exists:

yield-loop.js
// Fixed: yield through a task without the timer clamp.
const channel = new MessageChannel();
const waiting = [];
channel.port1.onmessage = () => waiting.shift()?.();

function yieldToLoop() {
  if (globalThis.scheduler?.yield) return scheduler.yield();
  return new Promise((resolve) => {
    waiting.push(resolve);
    channel.port2.postMessage(null);
  });
}

async function processAll(items, handle) {
  for (const item of items) {
    handle(item);
    await yieldToLoop();
  }
}

The MessageChannel fallback is Baseline widely available (channel messaging on webstatus.dev, as of 18 October 2026). scheduler.yield() is part of the Scheduler API, which is limited availability and discussed below, so keep the fallback. Yielding through a task gives the browser a chance to select input or rendering in step 2.1, but it doesn't force it to. That's the whole contract.

Engines agree on the ordering tests and drift at the edges

The spec tells you what's guaranteed. Web Platform Tests and a probe tell you what's shipped. I checked both on 18 October 2026.

WPT's ordering tests pass in all four stable engines

The wpt.fyi stable runs dated 17 October 2026 are Chrome 155.0.8059.84, Edge 155.0.4283.62, Firefox 158.0 and Safari 27.0. In html/webappapis/scripting/event-loops, the task and microtask ordering tests pass everywhere: task_microtask_ordering.html (2 of 2 subtests), microtask_after_raf.html, microtask_after_script.html and both microtask_before_prepare_the_script_element tests pass in all four. So does new-scroll-event-dispatched-at-next-updating-rendering-time.html.

Two tests in the directory don't pass everywhere, and both are about the inside of the rendering update rather than the turn. raf-from-animation-event-serviced-in-same-rendering-update.html fails in Chrome and Edge 155 and passes in Firefox 158 and Safari 27. update-the-rendering-resize-autofocus.html fails only in Edge 155, so Chrome and Edge results can differ on the same Chromium milestone. Both belong to the next part of this series.

Interop 2026 made scroll-event timing a shared target

Mozilla's launch post (12 February 2026, by Jake Archibald) lists "The event loop" among the existing features whose edge cases Interop 2026 will work on. WebKit's announcement files the same work under Web Compat, as "Timing of scroll events relative to animation events", which it describes as making sure "scroll and animation events fire in a predictable, interoperable order". The official Interop 2026 README puts it in Web Compat next to ESM module loading and unprefixing -webkit-user-select, and cites the event loop processing model as the spec.

The proposal behind it, interop issue #1126, is direct: "Chrome's behaviour related to when it dispatches scroll events relative to animation events diverges from the spec (and from WebKit and Geckos behaviour)". It links three Firefox web-compat bugs and Chromium issue 397737222, and it was closed as accepted in February 2026. Its test link is the new-scroll-event-dispatched-at-next-updating-rendering-time.html test that now passes in Chrome 155 stable.

The Web Compat scores move in the same direction. In the Interop 2026 stable score data, the area started 2026 at 84.4% for Chrome, 88.8% for Edge, 73.3% for Firefox and 44.4% for Safari, with an interop score (passing in all four) of 33.3%. On 17 October 2026 it reads 100% for Chrome, Edge and Firefox and 77.7% for Safari, with an interop score of 77.7%. Chrome's figure first reaches 100% in the Chrome 153 rows in September. The area also covers ESM loading and user-select, and the scroll-timing test passes in Safari 27, so Safari's remaining gap is elsewhere in the area; I didn't break it down test by test.

My probe found engines disagreeing on the first unguaranteed pair

The method, so you can repeat it. I used Playwright 1.64.1 from Node 24.18.0 on an Apple M1 Max running macOS 27.0.1, driving headless Google Chrome 155.0.8059.80 (the installed stable release), Playwright's Firefox 155.0 build and Playwright's WebKit 27.2 build. The Firefox and WebKit builds are Playwright's patched engines, not Firefox or Safari releases, and everything ran headless. All three reported document.visibilityState as "visible" and document.hasFocus() as true. For the ordering probe, each of 1,000 iterations starts from a fresh MessageChannel task (two hops, so the timer nesting level is 0), schedules one callback through each mechanism, and records the order in which they run. This is the core of it:

order-probe.js
// Runs inside the page. Resolves with the order of callbacks.
function probeOnce() {
  return new Promise((resolve) => {
    const log = [];
    const push = (name) => {
      log.push(name);
      if (log.length === 7) resolve(log.join(' > '));
    };
    const channel = new MessageChannel();
    channel.port1.onmessage = () => push('MessageChannel');
    addEventListener('message', function onMessage(event) {
      if (event.data !== 'probe') return;
      removeEventListener('message', onMessage);
      push('postMessage');
    });

    setTimeout(() => push('setTimeout(0)'), 0);
    postMessage('probe', location.origin);
    channel.port2.postMessage(null);
    requestAnimationFrame(() => push('rAF'));
    Promise.resolve().then(() => push('promise'));
    queueMicrotask(() => push('queueMicrotask'));
    push('sync');
  });
}

(My harness used one long-lived channel and listener rather than creating them per run, and posted to '*' on a setContent page; the shape is otherwise the same.)

The results, as counts out of 1,000:

Engine (build) Order observed Count
Chrome 155.0.8059.80 sync, promise, queueMicrotask, setTimeout(0), postMessage, MessageChannel, rAF 1,000
Firefox 155.0 (Playwright) sync, promise, queueMicrotask, setTimeout(0), postMessage, MessageChannel, rAF 999
Firefox 155.0 (Playwright) sync, promise, queueMicrotask, rAF, setTimeout(0), postMessage, MessageChannel 1
WebKit 27.2 (Playwright) sync, promise, queueMicrotask, postMessage, setTimeout(0), MessageChannel, rAF 1,000

The guaranteed part is identical everywhere: synchronous code, then the promise reaction, then the queueMicrotask callback, in registration order. The unguaranteed part differs. Chrome and Firefox ran the timer before the posted message; the WebKit build ran the posted message first. requestAnimationFrame usually came last because three cheap tasks finish long before the next rendering opportunity, but in one Firefox run out of 1,000 the rendering task won the selection before any of them. That single run is the processing model in miniature: nothing stops a rendering task from being picked ahead of tasks that were queued earlier.

The clamp table in the previous section came from the same setup: chains of ten and sixteen timers, 100 repetitions for ten-step chains and 60 for sixteen, medians per step. I repeated the probes later the same day: the order counts came out exactly as above, the thresholds didn't move, and two back-to-back clamp runs gave identical medians (the ones in the table). An earlier clamp run that day put the clamped medians about a millisecond lower in Chrome and Firefox, which is why I'd only trust them to the nearest millisecond.

Scheduling APIs change the selector, not the contract

The Prioritized Task Scheduling draft (a WICG Draft Community Group Report, last updated 30 May 2025) is the clearest example of how to extend the event loop without breaking it. It patches the processing model: before step 2, collect the task queues with runnable tasks and select "the next scheduler task queue from all schedulers"; then step 2.1 becomes a choice between an HTML task queue and the scheduler's queue, again "chosen in an implementation-defined manner".

The draft is open about the gap between that wording and what it hopes for. Its note says "the intent of this specification is that the TaskPriority of Scheduler tasks would influence the event loop priority", with "background" tasks usually below other work and "user-blocking" tasks and continuations above it, and it sketches one strategy without requiring it. So scheduler.postTask() priorities are a strong hint that participates in the same selection step, not a guarantee of ordering against timers, messages or input. The Scheduler API is limited availability on webstatus.dev as of 18 October 2026, listed in Chrome and Edge 129 and Firefox 142, with no Safari release. A later part of this series covers what postTask and yield() can promise in detail.

Two guarantees survive, and the rest is engine policy

Here's how I'd turn the model into rules for code review.

Rely on same-source order and the microtask drain

Within one task source, tasks run in the order they were queued. All microtasks queued during a task run before the next task is selected, and microtasks run in the order they were queued, promise reactions and queueMicrotask() alike. Microtasks also run whenever the browser finishes invoking a callback with an empty stack: between real event listeners and between requestAnimationFrame callbacks. A timer never fires before an earlier timer on the same global whose delay was equal or shorter, at least while the page is visible. The engines' WPT results for task and microtask ordering are green across Chrome, Edge, Firefox and Safari stable as of 17 October 2026, so these aren't only spec promises.

Stop relying on cross-source order, frames and clamps

Order between different task sources: timers against postMessage, postMessage against MessageChannel, one port against another, network callbacks against any of them. My probe showed WebKit and Chrome disagree on the first pair, and the spec allows any answer. Rendering after a given task: the rendering task competes in the same implementation-defined selection, and the browser may coalesce tasks without rendering between them. A fixed frame interval: rendering opportunities follow the display, the engine's throttling and visibility. The exact timer clamp: three engines gave me three different thresholds.

Chain work explicitly instead of racing two sources

If two things must happen in order, put them in the same task source or chain them explicitly (await one before scheduling the other); don't schedule them through two different mechanisms and hope. If you want "after the browser has had a chance to paint", schedule from inside requestAnimationFrame and then hop to a task, and measure it, because the spec doesn't promise a paint in between. Replace await sleep(0) yield loops with scheduler.yield() where available and a MessageChannel hop elsewhere. In tests, remember that element.click() and a real click produce different microtask interleavings; if your component's behavior depends on that, the test that uses click() is testing a different program. And when someone in a review says "the event loop guarantees X", ask which task source X is on.

What we don't know

  • How each engine maps task sources to queues and chooses between them. It's implementation-defined by design. My probe shows each engine's choice for one scenario in one configuration; it doesn't tell you the policy, and I didn't read engine source or documentation for it. Reading the schedulers in Blink, Gecko and WebKit, or getting engine engineers to document them, would settle it.
  • Whether my results hold in shipping Firefox and Safari. The Firefox and WebKit numbers come from Playwright's patched builds (Firefox 155.0 and WebKit 27.2), headless, on one Mac. Repeating the probe in Firefox 158 and Safari 27 with a visible window would settle whether the postMessage before setTimeout ordering and the ten-level clamp are WebKit behavior or artifacts of the build.
  • Hidden tabs. I didn't run the probe in a hidden page. The spec permits rendering opportunities to drop to "4 rendering opportunities per second, or even less" for invisible content, and issue #5925 says hidden-page timer throttling can break the timer ordering guarantee. What each engine does there today is unmeasured here.
  • Whether the spec or the engines will move on timer nesting. Issue #10386 is open. The spec and WPT say a timer scheduled from a microtask starts at nesting level 0; every stable engine clamps it anyway, and WebKit's bug for it is reopened. Whether the engines change or the spec adopts what they ship is open.
  • The state of the Chromium scroll-timing bug. The Interop test linked from proposal #1126 passes in Chrome 155 stable, and Chrome's Web Compat score reached 100% in September 2026, but I couldn't read the status of Chromium issue 397737222 from its public page, so I can't say whether it's closed as fixed.
  • Whether Chrome's failing rAF-from-animation-event test shares a root cause with the scroll-timing work. Nothing I read connects them or rules it out.
  • How much measurement overhead is in the clamp numbers. The 5 ms, 6 ms and 7–8 ms medians include scheduling overhead and each engine's performance.now() resolution, which I didn't control for, and one earlier run came out about a millisecond lower in Chrome and Firefox. The thresholds (which step clamps first) were stable across every run; the exact delays are not precise.

References

  1. HTML Standard: Event loop processing model. WHATWG. Accessed .
  2. HTML Standard: Event loop definitions (task queue). WHATWG. Accessed .
  3. HTML Standard: Queuing tasks. WHATWG. Accessed .
  4. HTML Standard: Perform a microtask checkpoint. WHATWG. Accessed .
  5. HTML Standard: Rendering opportunity. WHATWG. Accessed .
  6. HTML Standard: Generic task sources. WHATWG. Accessed .
  7. HTML Standard: Clean up after running script. WHATWG. Accessed .
  8. HTML Standard: HostEnqueuePromiseJob. WHATWG. Accessed .
  9. HTML Standard: Spin the event loop. WHATWG. Accessed .
  10. HTML Standard: Timer initialization steps. WHATWG. Accessed .
  11. HTML Standard: Run steps after a timeout. WHATWG. Accessed .
  12. HTML Standard: Posted message task source. WHATWG. Accessed .
  13. HTML Standard: Port message queue. WHATWG. Accessed .
  14. HTML Standard: Run the animation frame callbacks. WHATWG. Accessed .
  15. ECMAScript Language Specification: HostEnqueuePromiseJob. Ecma TC39. Accessed .
  16. ECMAScript Language Specification: Jobs and Host Operations to Enqueue Jobs. Ecma TC39. Accessed .
  17. whatwg/html pull request #10007: Refactor event-loop processing model to perform rendering as a task. WHATWG (GitHub). Accessed .
  18. whatwg/html issue #10386: setTimeout() nesting levels: browsers do not match specification. WHATWG (GitHub). Accessed .
  19. whatwg/html issue #5925: Timer order and timer throttling for hidden pages. WHATWG (GitHub). Accessed .
  20. Interop 2026 README: Web compat. Interop project (web-platform-tests). Accessed .
  21. Interop proposal #1126: Timing of scroll events relative to animation events. Interop project (web-platform-tests). Accessed .
  22. Interop 2026 stable scores (CSV). web-platform-tests results-analysis. Accessed .
  23. Launching Interop 2026. Mozilla Hacks. Accessed .
  24. Announcing Interop 2026. WebKit blog. Accessed .
  25. Chromium issue 397737222: scroll events (and some other events) get fired along with animation related events. Chromium. Accessed .
  26. wpt.fyi API: latest stable runs. Web Platform Tests. Accessed .
  27. wpt.fyi API: html/webappapis/scripting/event-loops results for the 2026-10-17 stable runs. Web Platform Tests. Accessed .
  28. WPT: timer-nesting-not-inherited-in-microtask.html. Web Platform Tests (GitHub). Accessed .
  29. WebKit bug 301008: DOM timers installed during a microtask checkpoint should not inherit DOM timer nesting level from the task scope. WebKit Bugzilla. Accessed .
  30. wpt.fyi API: html/webappapis/timers results for the 2026-10-17 stable runs. Web Platform Tests. Accessed .
  31. WPT: task_microtask_ordering.html. Web Platform Tests (GitHub). Accessed .
  32. WPT: microtask_after_raf.html. Web Platform Tests (GitHub). Accessed .
  33. Prioritized Task Scheduling: HTML event loop processing model patches. WICG. Accessed .
  34. Scheduler API. Web Platform Status (webstatus.dev). Accessed .
  35. requestIdleCallback(). Web Platform Status (webstatus.dev). Accessed .
  36. HTML Standard: Microtask queuing (queueMicrotask). WHATWG. Accessed .
  37. Channel messaging. Web Platform Status (webstatus.dev). Accessed .
  38. queueMicrotask(). Web Platform Status (webstatus.dev). Accessed .
  39. Long animation frames performance entries. Web Platform Status (webstatus.dev). Accessed .
  40. Long Animation Frames API (Editor's Draft, 15 October 2026). W3C Web Performance Working Group. Accessed .
  41. Using microtasks in JavaScript with queueMicrotask(). MDN. Accessed .
  42. Tasks, microtasks, queues and schedules. Jake Archibald. Accessed .
  43. Playwright. Microsoft. Accessed .

Found this useful? Pass it on.

Set in Archivo on a twelve-column grid. Built with Lit web components and rendered to static HTML.

© 2026 Oleg Chursin
Brooklyn, New York