Debugging Web Performance / Module 05

Module 5: Taps That Feel Frozen

Split a slow tap into its three parts, find the script with Long Animation Frames, and fix it by updating less and yielding with scheduler.yield().

Leo tried the stadium seat map on his phone. He tapped one seat, and nothing happened. He tapped it again. The seat turned orange for a moment, then blue again.

“Is the seat mine or not?” Leo wrote.

“Not now,” Maya wrote back. “Your phone was still busy with the first tap when you made the second one, and the second one took the seat back.”

Maya, Leo and TinyTickets are invented, and so are the numbers in their story.

This module is about interactions that answer late. You’ll split one slow tap into its three parts and follow the browser’s event loop to see why a change waits to reach the screen. You’ll find the code with Long Animation Frames and the web-vitals attribution build. Then you’ll fix the seat map’s tap one change at a time, and measure what each change costs.

After this module, you can:

  • split a slow interaction into input delay, processing duration and presentation delay, and say which kind of fix each part points to
  • explain how the browser’s event loop runs tasks, microtasks and rendering, and predict whether a change reaches the screen before the rest of a handler runs
  • find the script and the source position behind a slow interaction with the Long Animation Frames API, in the lab and in field data from the web-vitals attribution build
  • shorten a handler by updating only what changed, changing the screen first and yielding with scheduler.yield() and a fallback, and name what each step costs
  • decide whether a web worker fits a piece of work, from what it costs to copy the data to it

What buyers felt when they tapped a seat

Since Module 4, every view of the seat map appears quickly: from the back/forward cache, from cached files, or from a prerender. But answering a tap is another matter. On phones, CrUX still gives the seat map an INP of 1,200 ms at the 75th percentile, and anything over 500 ms is poor (Module 1).

Maya’s own endpoint has sent INP with its parts since Module 1. In the last week, 1,960 INP lines came from phones on the seat map, with a 75th percentile of 1,150 ms. In 1,730 of them, processing was the largest of the three parts, and every one of those named DIV#map.onclick in seats.js. Module 2 followed that handler to render(), which writes to all 60,000 seat elements after every tap.

Pause and predict. Suppose the click handler took 0 ms. On the phone profile, what would the tap’s INP be? Write a number down; Fix 2 answers it.

Reproduce the slow tap in the lab

The lab app is Module 4’s, unchanged. Set the phone profile from Module 1: 412 × 823, device pixel ratio 1, touch, Slow 4G and 6x CPU. Check Disable cache, as in Modules 1 to 3; a tap doesn’t depend on the cache.

The runs behind this module used headless Chrome 157 on the 2019 laptop (Intel Core i7-9750H), driven through the DevTools Protocol, as in Modules 1 to 3. Each run loaded the seat map, waited 8 seconds for the map to settle, and tapped three free seats near the top-left corner, about 3 seconds apart. Each version of the code ran three times, so each result below is a range over nine taps. Your numbers will differ.

The three parts come from each tap’s click entry in Event Timing. web-vitals starts the processing at the tap’s first event, pointerdown, so its processing duration is about 25 to 30 ms longer and its input delay shorter by the same amount.

Seat map from Module 4, nine taps Range
From the tap to the next frame 736–784 ms
Input delay 93–118 ms
Processing duration 357–391 ms
Presentation delay 285–301 ms

The taps match Module 1’s 768 ms on the same profile. Without throttling, Module 1 measured 160 ms on the laptop, under the 200 ms threshold. That’s why Maya never felt it. Figure 1 draws one of the nine taps on the main-thread timeline, at 20 ms per character as in Module 2. The paint box comes from a trace of a later tap, recorded for step 6 below.

time (ms)     0         200       400       600       800
              |         |         |         |         |
tap           v
main thread     [== handler, 453 ms ==][== paint ==]|
inside          [h][= click, 363 ms =]
INP parts     |----|-----------------|--------------|
              104  363 processing    301 presentation

h      = hit testing: finding the seat under the finger
paint  = a second task, about 260 ms: Paint and Layerize for the grid
|      = the frame with the orange seat, 768 ms after the tap

Figure 1: the tap’s own task, then a task that paints the whole grid; the seat turns orange 768 ms after the tap.

How a tap becomes a frame

Module 2 showed what the main thread did during the tap. This section explains why the frame had to wait for all of it, one idea at a time.

The three parts of one interaction

Module 1 timed an interaction from the input until the next frame is presented. That time has three parts, and each part has its own causes (web.dev, INP):

  • Input delay is the time from the input until the first event handler starts. It grows when the main thread is busy with other work when the input arrives: a long task, a timer, or the handler of an earlier interaction.
  • Processing duration is the time the interaction’s event handlers take to run, from the start of the first one to the end of the last one.
  • Presentation delay is the time from the end of the handlers until the frame is on the screen. It holds requestAnimationFrame callbacks, the rendering steps from Module 2, and the work after the main thread hands the frame on.

Figure 2 sets the three parts side by side.

Part Ends when Grows with In the seat map’s tap
Input delay the first handler starts other work on the main thread when the input arrives 93–118 ms
Processing duration the last handler returns the handlers’ own code 357–391 ms
Presentation delay the frame is on the screen rendering work, which grows with the size of the DOM 285–301 ms

Figure 2: the largest part says where to look first. Sources: web.dev, optimize INP, INP breakdown insight.

The DevTools INP breakdown insight reads the parts the same way. A long input delay means other main-thread work delayed the interaction, and that work “may not have been the direct cause”. A long processing duration means the handlers are the direct cause. A long presentation delay means rendering after the handlers.

The event loop runs one task, then the microtasks, then maybe a frame

The browser’s main thread runs an event loop, defined in the HTML Standard (processing model). Each turn of the loop does three things:

  1. It picks one task from one of its task queues and runs it to the end. Which queue it picks from is “implementation-defined”, so a browser may serve input before timers.
  2. It runs every microtask. A microtask is a callback that runs as soon as the current task’s script ends, before any other task. Promise reactions, the code after an await and queueMicrotask() callbacks are microtasks. Microtasks queued during this step run in the same step, so a chain of promises that keeps adding microtasks never lets the loop go on.
  3. If the page has a rendering opportunity, a moment when the browser has decided to produce a new frame, it updates the rendering. The spec gives 60 per second on a 60 Hz screen as an example, and lets a browser render less often for a page that’s struggling or hidden.

Figure 3 draws the loop.

           +-------------------------------------------------+
           v                                                 |
 [pick one task from a task queue] --> [run it to the end]   |
   input events, timers, messages,               |           |
   network callbacks, rendering                  v           |
                                    [run every microtask]    |
                                    promise reactions, code  |
                                    after await              |
                                                 |           |
                                                 v           |
                        rendering opportunity? --no----------+
                                | yes                        |
                                v                            |
   [update the rendering: requestAnimationFrame callbacks,   |
    style and layout, observers, paint] ---------------------+

Figure 3: a change to the DOM reaches the screen only in the rendering step, after the current task and all its microtasks.

Since a 2024 change to the HTML Standard, the rendering update is itself a task, queued when a rendering opportunity comes (whatwg/html PR 10007, merged 2024-01-31). But the rule is the same as before: rendering can’t start while another task is running.

Two details of the rendering step matter for handlers. requestAnimationFrame callbacks run inside it, before style and layout of the same frame, so they run before the next paint, not after it. And when there’s nothing to paint and no animation frame callback, a browser may skip rendering for that turn.

Rule: A change you make in a handler reaches the screen only after the task, every microtask it queued, and the rendering step have finished.

How the browser’s loop differs from Node.js

You may know the event loop from Node.js; the site’s article How Node.js works: the event loop explains its rules. The two loops share run-to-completion callbacks and a microtask queue. But they differ in the parts that decide how fast a page answers. Figure 4 compares them.

Browser main thread Node.js
Order of the queues chosen by the browser, so input can go first fixed phases: timers, pending callbacks, poll, check, close
Microtasks after every task after every callback, with process.nextTick() callbacks first
Rendering a step of the loop, at each rendering opportunity none: Node.js has no document and no frames
What a long callback delays input, timers and the next frame every other callback, including I/O

Figure 4: in the browser, a long task also delays the screen. Sources: HTML Standard, Node.js event loop guide.

setImmediate() and process.nextTick() don’t exist in the browser.

Long animation frames: the main thread, counted per frame

Module 2 found a gap in the Long Tasks API: it reported the script task but not the tasks that only rendered. A frame can also be late because of several tasks, none of them over 50 ms.

The Long Animation Frames API reports every long animation frame, a frame whose main-thread work took more than 50 ms (Chrome for Developers). The work counts from the start of the frame’s first task to the end of its rendering. You observe entries of type long-animation-frame with a PerformanceObserver. Each entry has these fields:

  • startTime and duration: from the first task of the frame to the end of its rendering on the main thread.
  • renderStart and styleAndLayoutStart: when the rendering step began, and when its style and layout began.
  • paintTime and presentationTime (Chrome 145): when the rendering step ended, and when the frame was presented on the screen.
  • firstUIEventTimestamp: the time of the first input event handled in the frame.
  • blockingDuration, explained below.
  • scripts: one entry for each script that ran for more than 5 ms. Each has an invoker (such as DIV#map.onclick), an invokerType (such as event-listener or resolve-promise), a duration and a forcedStyleAndLayoutDuration. sourceURL, sourceFunctionName and sourceCharPosition say where it came from.

The blocking duration of a frame is how much of it could have delayed an input. Chrome adds the rendering time to the frame’s longest task, then sums the part of each task over 50 ms. Two tasks of 55 ms and 65 ms with 20 ms of rendering give 5 + 35 = 40 ms.

The API attributes scripts on the main thread and in same-origin iframes, not in cross-origin iframes, workers or extensions. It shipped in Chrome 123 (March 2024), after an origin trial in Chrome 116 to 122. Firefox and Safari don’t have it. Chrome still supports the Long Tasks API, and since Chrome 124 computes it from the same data (chromestatus).

Find the cause in the frame

Module 2 read this tap in a trace. But a trace needs a recording, and buyers’ phones don’t record. So the steps below find the same cause with tools that also work in the field: live metrics, long animation frames and the web-vitals attribution build.

  1. Read the interaction in live metrics. Open the Performance panel and tap a blue seat. The Interactions log lists the tap as a pointer interaction, with its target and its duration in red. Expand it to see the three parts (Chrome 132 and later).

  2. Name the largest part. Processing was 357–391 ms, about half of each tap, so the handlers are the direct cause. The input delay of about 100 ms isn’t small either; step 5 comes back to it.

  3. Observe the long animation frames. Paste this into the Console, then tap one blue seat:

const ms = (n) => `${Math.round(n)} ms`;
new PerformanceObserver((list) => {
  for (const frame of list.getEntries()) {
    console.log(`frame at ${ms(frame.startTime)}: ${ms(frame.duration)}, blocking ${ms(frame.blockingDuration)}, ` +
      `rendering at +${ms(frame.renderStart - frame.startTime)}, painted at +${ms(frame.paintTime - frame.startTime)}, ` +
      `presented at +${ms(frame.presentationTime - frame.startTime)}`);
    for (const s of frame.scripts) {
      console.log(`  ${s.invoker} (${s.invokerType}) ${ms(s.duration)}, ` +
        `function "${s.sourceFunctionName}" at ${s.sourceURL.split('/').pop()}:${s.sourceCharPosition}`);
    }
  }
}).observe({ type: 'long-animation-frame' });

The observer has no buffered: true, so it prints only the frames after you paste it, not the page load. One run printed:

frame at 15691 ms: 442 ms, blocking 391 ms, rendering at +442 ms, painted at +442 ms, presented at +701 ms
  DIV#map.onclick (event-listener) 347 ms, function "" at seats.js:1525

Pause and predict. The script entry says seats.js:1525. That number is a character position, not a line. Which line of seats.js is it, and why is the function name empty?

Answer

Count the lines in the first 1,525 characters of the file:

fetch('/seats.js').then((r) => r.text()).then((text) => text.slice(0, 1525).split('\n').length);

It returns 41, the line map.addEventListener('click', (event) => {. The position points at the start of the arrow function. An arrow function passed straight to addEventListener has no name, so sourceFunctionName is empty. In a minified bundle the position is still there, and a source map turns it into a line of your source.

  1. Read the frame’s times. The frame lasted 442 ms, and the handler was 347 ms of it. Its blocking duration, 391 ms, is the frame minus 50 ms: an input that arrived during it could have waited that long. Rendering started at +442 ms, the end of the frame, so the entry gives it no time. A trace of a similar tap shows 36 ms of style, layout and pre-paint at the end of the same task, small next to the handler.

  2. Look before the frame. The input delay starts before the frame does. In a trace of one such tap, the main thread ran three short tasks of hit testing before and around the click handler, 92 ms in all. That’s the browser finding which of 60,000 elements is under the finger. Module 2 found the same hit tests. Their cost comes from the size of the grid, not from the handler.

  3. Look after the paint. The frame was presented 259 ms after its rendering step ended. The trace shows a second main-thread task of 259 ms in that gap. In it, Chrome painted the grid and grouped it into layers (Paint, then Layerize for 56 ms). Your code isn’t in that task, and only one seat changed, but the paint covered the whole grid. Module 6 explains why. The long animation frame entry doesn’t count that task in its duration; it shows only as the gap between paintTime and presentationTime.

  4. Check the field lines. When the tab was hidden, vitals.js sent its report to /vitals. Here is the INP line from one tap in a separate run, without its time and id fields. These runs used port 18570 instead of 8080.

{"page":"/seats.html","device":"phone","name":"INP","value":816,"rating":"poor","navigationType":"navigate","interactionTarget":"#map>span.picked.seat","interactionType":"pointer","interactionTime":17375.799999952316,"nextPaintTime":18191.799999952316,"inputDelay":91.89999997615814,"processingDuration":414.8000000715256,"presentationDelay":309.2999999523163,"loadState":"complete","totalScriptDuration":388.39999997615814,"totalStyleAndLayoutDuration":0,"totalPaintDuration":271.10000002384186,"totalUnattributedDuration":156.5,"script":"DIV#map.onclick in http://localhost:18570/seats.js"}

script names the same handler, from longestScript. totalPaintDuration is the time from the last frame’s paintTime to its presentation, the paint task from step 6. totalUnattributedDuration is the rest of the 816 ms, neither script, style and layout, nor paint: here the hit testing and the wait before the frame. These fields told Maya that her buyers’ slow taps had the same shape as the lab’s.

Figure 5 maps the frame’s fields onto the tap.

+0 ms    startTime: the task that handles the tap begins
         |  scripts[0]: DIV#map.onclick, event-listener, 347 ms
         |  blockingDuration: 442 - 50 = 391 ms
+442 ms  renderStart = styleAndLayoutStart = paintTime: the rendering
         step, no time of its own in the entry
         |  not in the entry: a 259 ms task that paints the grid
+701 ms  presentationTime: the orange seat is on the screen

Figure 5: the entry names the script inside the frame; the time after paintTime is work it doesn’t attribute.

Rule: Read the largest part, then the frame: its scripts for processing, the work before it for input delay, the gap after paintTime for presentation delay.

The fixes, one change at a time

Each fix below changes one thing in public/seats.js. Every number comes from the phone profile in headless Chrome 157, three page loads with three taps each, unless a line says otherwise.

Fix 1: change the seat first, then yield

The buyer is waiting for one thing: the tapped seat turning orange. render() also rewrites 59,999 seats that didn’t change, the status line and the checkout link, and the frame waits for all of it. So the first fix changes the tapped seat at once, lets the browser show it, and runs render() after that.

That needs yielding. Yielding is ending the current task on purpose and continuing the work in a later task, so the browser can render and handle input in between. Splitting code into smaller functions doesn’t yield, because they still run in one task (web.dev). An await yields only when what it waits for resolves in a new task.

scheduler.yield() returns a promise that resolves in a new task. The code after await scheduler.yield(), called the continuation, runs once the browser has had a chance to render and handle input. It runs before other tasks of the same priority that were already waiting, such as timers (Chrome for Developers, MDN). It works in Chrome 129 and Firefox 142, not in Safari, so the code falls back to setTimeout.

Add a helper above the click listener, and replace the listener:

// Lets the browser paint and handle input, then continues. Safari has no scheduler.yield().
function yieldToMain() {
  if (globalThis.scheduler?.yield) return scheduler.yield();
  return new Promise((resolve) => setTimeout(resolve, 0));
}

map.addEventListener('click', async function pickSeat(event) {
  const id = elements.indexOf(event.target);
  if (id === -1 || seats[id].sold) return;
  picked.has(id) ? picked.delete(id) : picked.add(id);
  // The buyer waits for this one seat to change color, so change it first.
  event.target.className = `seat ${picked.has(id) ? 'picked' : 'free'}`;
  await yieldToMain();
  render();
});

Three things changed. The handler sets the tapped seat’s class itself, before anything else. It awaits yieldToMain(), so render() runs in a later task. And the handler has a name, pickSeat, so long animation frames can report it.

The tap now took 360–464 ms. Processing fell from 357–391 ms to 0–3 ms, and input delay and presentation delay stayed where they were. The long animation frame snippet printed two frames for one tap:

frame at 15041 ms: 71 ms, blocking 21 ms, rendering at +71 ms, painted at +71 ms, presented at +343 ms
frame at 15380 ms: 383 ms, blocking 326 ms, rendering at +363 ms, painted at +383 ms, presented at +588 ms
  Scheduler.yield.then (resolve-promise) 356 ms, function "" at seats.js:1665

The first frame shows the orange seat; its handler ran under the 5 ms reporting limit, so it lists no script. The second frame is render(), now invoked by Scheduler.yield.then with the type resolve-promise. Figure 6 puts the tap on the timeline, from one run and its trace.

time (ms)     0         200       400       600       800       1,000
              |         |         |         |         |         |
tap           v
main thread     [h][== paint ==][= render(), 379 =][= paint =]   NEW
frames                          | orange seat               | status line
INP parts     |----|------------|
              96   264 presentation (processing 1 ms)

h = the tap's task: hit testing and a handler of 1 ms

Figure 6: the seat is on the screen at 360 ms; render() and a second paint run after it.

The yield didn’t let render() start right after the handler. In the trace, the paint task for the orange seat ran first, 263 ms, and the continuation started after it. Then render() ran 374 ms and caused another full paint of 263 ms.

Pause and predict. yieldToMain() looks like more code than it needs. What happens if you replace await yieldToMain() with await Promise.resolve()?

Answer

Nothing improves. In nine taps, the tap took 744–848 ms with processing 356–413 ms, the same as before the fix. Promise.resolve() is already resolved, so the code after the await runs as a microtask, in the same task, before any rendering. Each tap’s long animation frame listed one script, DIV#map.onclick, of 356–411 ms.

Figure 7 compares the ways to continue later, all with the same handler.

How the handler continues Tap to next frame Processing The frame with render()
No yield (Module 4 code) 736–784 ms 357–391 ms the tap’s own frame, 444–478 ms
await Promise.resolve() 744–848 ms 356–413 ms the tap’s own frame
await scheduler.yield() 360–464 ms 0–3 ms a later frame, 376–445 ms, invoker Scheduler.yield.then
setTimeout fallback (forced) 368–392 ms 0–2 ms a later frame, 376–415 ms, invoker TimerHandler:setTimeout

Figure 7: a microtask continues in the same task; a yield continues in a new one.

Why the fallback is setTimeout, and what it costs

On this page, the fallback measured the same as scheduler.yield(). But the two differ in where the continuation waits. scheduler.yield() queues it ahead of tasks that were already waiting at the same priority; setTimeout(resolve, 0) puts it behind them. This Console run shows the order:

const order = [];
setTimeout(() => order.push('setTimeout, queued first'), 0);
scheduler.postTask(() => order.push('postTask user-visible'), { priority: 'user-visible' });
scheduler.postTask(() => order.push('postTask user-blocking'), { priority: 'user-blocking' });
await scheduler.yield();
order.push('after scheduler.yield()');
await new Promise((resolve) => setTimeout(resolve, 50));
console.log(order);

scheduler.postTask() queues a task at one of three priorities: user-blocking, user-visible (the default) or background. Three runs in headless Chrome 157, with no throttling, all printed:

["postTask user-blocking","after scheduler.yield()","setTimeout, queued first","postTask user-visible"]

The continuation ran before a timer that was queued earlier, and after only the user-blocking task. So if you use setTimeout, a third-party script’s timers that are already queued run before the rest of your handler.

setTimeout has a second cost. The HTML Standard raises a timer’s delay to at least 4 ms once timers are nested more than five deep, each set from inside the one before (HTML Standard, timers). So a loop that yields many times with setTimeout pays it on every yield after the fifth. In the same browser, ten nested setTimeout(tick, 0) calls were this far apart, in milliseconds:

nested setTimeout gaps: [0,0,0,0,0,0,4.7,4.1,4.6,4.1]

Ten await scheduler.yield() calls in a row were 0 to 0.1 ms apart. In Chrome and Firefox, yieldToMain() takes the first branch. In Safari, it takes the fallback, so the same code yields there too, a little later.

The cost of Fix 1

  • The work is moved, not removed. render() still runs for 351–419 ms in a frame of its own, with a blocking duration of 320–389 ms. An input that arrives during it waits up to that long, as Leo’s second tap waited behind his first before any fix. The runs here couldn’t show it with a second tap: the protocol delivered the next tap only after the frames of the first were presented.
  • More main-thread time in all. In the trace, one tap now cost a 70 ms handler task, two paints of 263 ms each and a 374 ms render(), about 970 ms in all. Before Fix 1, it was 472 ms plus one paint of 259 ms. Each extra frame repaints the whole grid.
  • Two states on screen for a moment. For about 0.4 s, the seat is orange while its label, its aria-pressed and the status line still say otherwise. So a screen reader that reads the seat in that window hears the old state.

Alternatives, and when they fit

Yield inside render() as well. Run the loop in chunks, and yield when 50 ms have passed since the last yield, which web.dev names as a common deadline:

// Excerpt: render() with a yield every 50 ms. The loop body is the same as before.
async function renderInChunks() {
  let last = performance.now();
  for (const seat of seats) {
    // ... update one seat, as in render() ...
    if (performance.now() - last > 50) {
      await yieldToMain();
      last = performance.now();
    }
  }
}

In a variant with this loop, the tap took 368–392 ms, as with Fix 1. The work after the tap ran as tasks of 50–53 ms, and the frames that held them had a blocking duration of 0–4 ms instead of 320–389 ms. So an input that arrives during render() waits at most about 50 ms. The total time of the chunked render() wasn’t measured.

Yielding after every seat would add one task per seat, so check the clock and yield only after the deadline.

Two more ways to keep a tap short:

  • requestAnimationFrame followed by setTimeout. web.dev shows this way to run code after the next frame in every browser (optimize INP). But it waits for a whole frame even when the browser could continue sooner.
  • Debouncing, for input that repeats quickly, such as typing in a search field: run the expensive work only when no new input has arrived for a short time (web.dev). It cuts the number of runs, but the buyer waits for the pause before the result appears.

All of these keep the 60,000 writes. The next fix removes them.

Fix 2: update only what changed

One tap changes one seat. So Fix 2 splits render() into the part one seat needs and the part the whole page needs, and the tap calls only those.

Replace render(), yieldToMain() and the click listener with this. yieldToMain() is the same as in Fix 1:

// Brings one seat element up to date with the seat list.
function renderSeat(seat) {
  const state = seat.sold ? 'sold' : picked.has(seat.id) ? 'picked' : 'free';
  const label = `Row ${seat.row}, seat ${seat.number}, $${seat.price}, ${state}`;
  const element = elements[seat.id];
  element.className = `seat ${state}`;
  element.title = label;
  element.setAttribute('aria-label', label);
  element.setAttribute('aria-disabled', seat.sold);
  element.setAttribute('aria-pressed', state === 'picked');
}

// The line above the map and the checkout link.
function renderSummary() {
  let free = 0;
  for (const seat of seats) if (!seat.sold && !picked.has(seat.id)) free++;
  status.textContent = `${free} seats free, ${picked.size} picked`;
  checkout.href = `/checkout.html?seats=${[...picked].join(',')}`;
}

// Brings every seat element up to date. Only the first load needs it.
function render() {
  const start = performance.now();
  for (const seat of seats) renderSeat(seat);
  renderSummary();
  performance.measure('render', { start });
}

// Lets the browser paint and handle input, then continues. Safari has no scheduler.yield().
function yieldToMain() {
  if (globalThis.scheduler?.yield) return scheduler.yield();
  return new Promise((resolve) => setTimeout(resolve, 0));
}

map.addEventListener('click', async function pickSeat(event) {
  const id = elements.indexOf(event.target);
  if (id === -1 || seats[id].sold) return;
  picked.has(id) ? picked.delete(id) : picked.add(id);
  renderSeat(seats[id]);
  await yieldToMain();
  renderSummary();
});

In the pageshow handler from Module 4, update only the seats the server reported:

  for (const id of sold) {
    seats[id].sold = true;
    picked.delete(id);
    renderSeat(seats[id]);
  }
  renderSummary();

renderSeat() is the body of the old loop, for one seat. The tapped seat now gets its color, its label and its ARIA state in the same frame. renderSummary() counts the free seats in the seat list, plain JavaScript over 60,000 objects that touches no element, and runs after the yield.

elements.indexOf(event.target) stays. Module 2 guessed that it was most of the listener’s own 27 ms. But these runs say otherwise. With Fix 1, the handler before the yield, indexOf included, took 0–3 ms, also for seats in the last rows, where indexOf searches almost the whole list.

A variant looked seats up in a Map from element to seat number instead. Its taps were no faster, and build-map took 260–280 ms with the Map against 231–260 ms without it, in six loads each.

The tap now took 368–392 ms, with input delay 105–121 ms, processing 0–2 ms and presentation delay 263–273 ms. The snippet printed one frame per tap, and no script in it:

frame at 15667 ms: 73 ms, blocking 23 ms, rendering at +73 ms, painted at +73 ms, presented at +341 ms

That answers the prediction from the start of the module. With a handler of almost 0 ms, the tap still takes 368–392 ms on the phone profile. Figure 8 shows one tap, from one run and its trace.

time (ms)     0         200       400       600       800
              |         |         |         |         |
tap           v
main thread      [h][== paint ==][== paint ==]                NEW
frames                           | orange seat| status line
INP parts     |-----|------------|
              112   264 presentation (processing 0 ms)

h = the tap's task: hit testing and a handler of under 5 ms

Figure 8: render() is gone from the tap; two paints of the grid are left.

The other paths agree. Taps on seats in the last rows took 352–376 ms, with processing 0–3 ms. After Back from checkout, the pageshow refresh used to make one long animation frame of 412–492 ms, with Response.json.then as the invoker (three runs, headless, cache on). With Fix 2, the restore made no long animation frame at all.

Does the yield still earn its place?

After Fix 2, the work after the yield is the count and two text updates. A variant without the yield measured what it does now. Figure 9 compares them; the paint tasks come from one trace of each.

Fix 2 Tap to next frame Processing Presentation delay Paint tasks after one tap
With the yield 368–392 ms 0–2 ms 263–273 ms two: 269 ms and 240 ms
Without the yield 408–464 ms 5–9 ms 293–325 ms one: 270 ms

Figure 9: the yield shortens the tap and adds a frame, and on this page each frame repaints the grid.

Without the yield, the status line changes in the tap’s frame, and the trace shows its cost there: style, layout and pre-paint, about 36 ms, plus the count. With the yield, the seat appears 16 to 96 ms sooner. But the status line gets a frame of its own, which repaints the whole grid for 240 ms. A tap in those 240 ms waits.

The lab keeps the yield, because INP measures the tap the buyer made, and that tap is answered sooner. But the choice flips when buyers tap in quick bursts, or when a frame costs more than the work you move out of it. Module 6 works on the cost of each paint, which decides how much the second frame costs.

The costs of Fix 2:

  • Two ways to update a seat. render() and renderSeat() must agree. Here render() calls renderSeat() for every seat, so there’s one place to change.
  • Every change must call renderSeat(). If you add a feature that changes seats without it, that feature leaves the map wrong. Frameworks that update the DOM from your data take over this bookkeeping, at costs of their own that this course doesn’t cover.
  • The status line comes one frame after the seat, about 240 ms later on the phone profile.

Where a web worker fits

After Fix 2, the only work that grows with the size of the stadium is the count in renderSummary(). It reads no element, so it could run on another thread.

A web worker is a script that runs on its own thread, with no access to the DOM, and talks to the page only through messages (MDN). What you pass to postMessage() is copied by the structured clone algorithm. It’s a deep copy that handles objects, arrays, Map, Set and more, written on one thread and rebuilt on the other. An ArrayBuffer can be transferred instead of copied, and then the sender can no longer use it.

Pause and predict. Counting the free seats takes a few milliseconds on the phone profile. A worker could count them while the main thread stays free. How long does the main thread spend handing the 60,000 seats to the worker?

Answer

Much longer than the count. In three runs at 6x CPU, on a blank page with the same seat list, the count took 5.7–14.7 ms on the main thread. postMessage() with the seats blocked the main thread for 103.5–115.8 ms, and the answer came back 131.0–146.8 ms after the call. The worker and the main thread counted the same 23,998 free seats.

The code behind those numbers, for the Console of a blank tab (about:blank), since it declares its own seats:

const seats = Array.from({ length: 60000 }, (_, i) => ({
  id: i, row: Math.floor(i / 200) + 1, number: (i % 200) + 1, price: i < 20000 ? 95 : 60, sold: (i * 7919) % 10 < 6,
}));
const picked = new Set([2, 3]);
const source = `onmessage = ({ data: { seats, picked } }) => {
  let free = 0; for (const s of seats) if (!s.sold && !picked.has(s.id)) free++; postMessage(free); };`;
const worker = new Worker(URL.createObjectURL(new Blob([source], { type: 'text/javascript' })));
let start = performance.now();
let free = 0;
for (const seat of seats) if (!seat.sold && !picked.has(seat.id)) free++;
console.log(`main thread: ${free} free in ${(performance.now() - start).toFixed(1)} ms`);
start = performance.now();
worker.onmessage = (e) => console.log(`worker: ${e.data} free, ${(performance.now() - start).toFixed(1)} ms after postMessage`);
worker.postMessage({ seats, picked });
console.log(`postMessage blocked for ${(performance.now() - start).toFixed(1)} ms`);

Figure 10 sets out the trade.

On the main thread In a worker, copying the seats on each tap
Main thread busy 5.7–14.7 ms 103.5–115.8 ms for postMessage() alone
Answer ready at once 131.0–146.8 ms later
Extra code none a worker file, messages, two copies of the seat list

Figure 10: a worker moves the work off the main thread, but the copy stays on it. Measured at 6x CPU, three runs.

A worker fits when the work is long compared with copying its input and its result. The choice flips when the data can stay in the worker: send the seat list once, then send only the seat that changed, and get back one number. It never fits the 60,000 elements: they must stay on the main thread, which is the only thread with the DOM (web.dev). TinyTickets keeps the count on the main thread.

What is left: hit testing and painting the grid

What’s left of the tap isn’t JavaScript you wrote. In the trace of one tap with Fix 2:

  • Hit testing, 88 ms in three tasks before and around the tap’s task: the browser finding which of 60,000 elements is under the finger. It’s most of the input delay.
  • One paint task, 269 ms: Paint and Layerize for the whole grid, for one changed seat. It’s the presentation delay.

Both grow with the number of elements in the grid, and neither shrinks when the handler does. At 368–392 ms, the tap is in “needs improvement”. This module doesn’t change the grid; Module 6 does.

Before and after

Figure 11 puts the module’s steps side by side, nine taps each.

Version Tap to next frame Input delay Processing Presentation delay Long animation frames per tap
Module 4 code 736–784 ms 93–118 ms 357–391 ms 285–301 ms one, 444–478 ms
Fix 1: seat first, yield, then render() 360–464 ms 96–147 ms 0–3 ms 264–316 ms two, 63–96 ms and 376–445 ms
Fix 2: update only what changed 368–392 ms 105–121 ms 0–2 ms 263–273 ms one, 65–77 ms

Figure 11: the handler went from 357–391 ms to under 3 ms, and the tap from about 770 ms to about 380 ms.

Confirming it in the field

Maya shipped Fixes 1 and 2 together. A week later, her endpoint had 2,080 INP lines from phones on the seat map, with a 75th percentile of 420 ms, “needs improvement” instead of poor. Presentation delay was now the largest part in 1,840 of them. The script field was empty in most lines, because no script over 5 ms ran in the tap’s frame.

CrUX still showed 1,200 ms, because its 28-day window held three weeks before the release. Maya kept checking it, and turned to the 380 ms that no handler explained.

In Firefox and Safari

  • INP works in all three engines: Event Timing with interactionId since Chrome 96, Firefox 144 (October 2025) and Safari 26.2 (December 2025). Chrome measures to the frame’s presentation, Firefox and Safari to its paint, so their numbers are a few milliseconds shorter (web.dev, 2025-12-17). CrUX counts Chrome only.
  • Long Animation Frames are Chrome-only. In Firefox and Safari, web-vitals still reports the three parts of INP, without longAnimationFrameEntries or longestScript.
  • scheduler.yield() works in Chrome 129 and Firefox 142, not in Safari. WebKit has published no position on the API. That’s why yieldToMain() has a fallback.
  • Web workers work in all three, with the same copying cost.

What changed recently

  • 2024-01-31: the HTML Standard made rendering a task of its own in the event loop (PR 10007). In March 2024, it added the hooks Long Animation Frames needs (PR 10198).
  • 2024-03-12: INP replaced First Input Delay as a Core Web Vital (Module 1).
  • Chrome 123 (March 2024): the Long Animation Frames API. Chrome 124 rebuilt the Long Tasks API on top of it.
  • Chrome 129 (September 2024): scheduler.yield(), and live metrics in the Performance panel (release notes).
  • Chrome 132 (January 2025): each interaction in the live metrics log expands to show its three parts (release notes).
  • August 2025: Firefox 142 shipped scheduler.postTask() and scheduler.yield() (release notes). In October 2025, Firefox 144 added interactionId, so INP (Mozilla).
  • Chrome 145 (February 2026): paintTime and presentationTime on long animation frame entries (chromestatus).
  • web-vitals 5 (May 2025) and 6 (July 2026): version 5 added the longestScript summary to INP’s attribution, and version 6 stopped filling processedEventEntries unless you ask for it (changelog).
  • isInputPending(), which older articles use to decide when to yield, is no longer recommended by the Chrome team. It can return false right after an input, and a page also needs to yield for rendering, not only for input (web.dev). Chrome 157 still has it.

Online tools for this step

Live metrics in the DevTools Performance panel show the page’s LCP, CLS and INP as you use it, without a recording. The Interactions log lists every tap and key press with its target and duration, colored by the INP thresholds, and each entry expands into its three parts. The Field data section can fetch CrUX data for the same URL and device class, so your lab number sits next to your users’ 75th percentile (Chrome for Developers).

  • Data: lab for your own session; field from CrUX, for Chrome users only, over 28 days, at the 75th percentile. You can map http://localhost:8080 to your production origin to get that origin’s field data.
  • Limit: the log records only while DevTools is open, and it names no script; for that, record a trace (Module 2) or read long animation frames. CrUX has no data for pages and origins with little traffic.
  • When something else is better: the page and your taps stay on your machine, so private pages are fine. The field data part asks Google’s CrUX API about the production URL and gets back public data. For your own users’ numbers, including Safari’s, use the next tool.

The web-vitals attribution build has sent TinyTickets’ field data to /vitals since Module 1. It gives each INP its three parts, its target and loadState. From long animation frames, it adds the longest script and the totals for script, style and layout, and paint.

  • Data: field, from your own users, in every browser with Event Timing. The long animation frame fields come only from Chromium browsers.
  • Limit: you build and run the endpoint and the queries yourself. It doesn’t see interactions inside iframes, which CrUX counts. The attribution build is about 1.5 KB (brotli) larger than the standard build.
  • When DevTools is better: to take one frame apart, or to test a page you haven’t shipped. Use the field lines to choose which interaction to reproduce, and DevTools to take it apart.

Check yourself

Debugging scenario

The show list page has a search field, and a keydown listener on it filters next month’s shows and redraws the list. Buyers say the letters appear late when they type fast. On the phone profile, Maya types three letters 120 ms apart. The filter handler takes 300 ms each time, and the rendering after it about 20 ms.

Live metrics report INP 720 ms for a keyboard interaction. The attribution build’s line for it says:

"interactionType":"keyboard","inputDelay":400,"processingDuration":300,"presentationDelay":20

Its longAnimationFrameEntries hold three frames, and each has one script:

INPUT#search.onkeydown (event-listener) 300 ms

Which key press is the 720 ms interaction, where does its input delay come from, and what would you change?

Hint 1

Draw the three handlers on one line. The keys arrive at 0, 120 and 240 ms, and each handler and its rendering take 320 ms. A task runs to its end before the next one starts.

Hint 2

The interaction has three frames, and only one of them is its own. Whose handlers are in the other two?

Answer

The third key press. The first handler runs from 0 to 300 ms, and its frame ends at 320 ms.

The second key, at 120 ms, waits until 320 ms, runs until 620 ms, and its frame ends at 640 ms. The third key, at 240 ms, waits until 640 ms: 400 ms of input delay. Its handler runs until 940 ms and its frame is presented at 960 ms, 720 ms after the key.

The input delay comes from the handlers of the first two keys, which are the first two long animation frames in its entries. Each key’s own handler is the direct cause of the next key’s wait.

Fixes, from the strongest: make the filter cheaper, so it updates only the rows that change instead of redrawing the list. Debounce the input, so only the last key in a quick burst runs the filter. Or show the typed text first, yield, and skip the filter when the field’s value has changed again since the handler started.

Review questions

  1. An interaction takes 600 ms: input delay 40 ms, processing 520 ms, presentation delay 40 ms. Where do you look first, and which field of a long animation frame entry names the code?
  2. A handler starts with await Promise.resolve() and then does 300 ms of work. Why doesn’t the change it made before the await reach the screen before the work?
  3. A long animation frame entry has invoker DIV#map.onclick, sourceFunctionName "" and sourceCharPosition 1525. What do you change so the next entry is easier to read, and how do you find the line today?
  4. Why does yieldToMain() fall back to setTimeout, and what two costs does the fallback have compared with scheduler.yield()?
  5. Counting free seats takes about 6 ms on the main thread, and copying the seat list to a worker blocks the main thread for about 105 ms. Should the count move to a worker, and what would change the answer?
Answers
  1. At processing, the largest part: the handlers are the direct cause. In the frame that holds the interaction, scripts lists each script over 5 ms, with invoker, sourceURL, sourceFunctionName and sourceCharPosition.
  2. Promise.resolve() is already resolved, so the code after the await runs as a microtask in the same task. The browser renders only after the task and all its microtasks end, so the frame waits for the 300 ms.
  3. Give the handler a name, such as async function pickSeat(event), so sourceFunctionName is filled. Today, count the lines in the first 1,525 characters of the file; in seats.js it’s line 41.
  4. Safari doesn’t support scheduler.yield(). A setTimeout continuation waits behind tasks that were already queued, such as other scripts’ timers, and nested timers are delayed to at least 4 ms after the fifth level.
  5. No. The copy costs about 17 times the count, and it happens on the main thread. It would change if the work were long compared with the copy, or if the seat list stayed in the worker and only the changed seat were sent.

Lab: find the slow handler and make the tap answer first

Time: about 15 minutes. You need the lab app from Module 4, Chrome and Node.js. The finished code for this module is in the course repository, folder module-05/.

  1. Start the server with node server.js. Open http://localhost:8080/seats.html in Chrome, open DevTools, and set the phone profile: 412 × 823 with touch, CPU “6x slowdown”, Network “Slow 4G”, Disable cache checked. Reload, and wait until the map is drawn.
  2. Open the Performance panel. Before you tap, predict which of the three parts will be the largest. Tap three blue seats a few seconds apart, then expand the slowest entry in the Interactions log and write down its three parts.
  3. Paste the long animation frame snippet from “Find the cause in the frame” into the Console, and tap one more seat. Write down the invoker, the function name and the character position, and turn the position into a line with the fetch snippet.
  4. Apply Fix 1. Reload, paste the snippet, and tap three seats. Compare the three parts, and find the second frame in the snippet’s output. What is its invoker now?
  5. Change await yieldToMain() to await Promise.resolve(), reload, and tap. Then change it back.
  6. Apply Fix 2. Repeat step 4, and count the frames the snippet prints for one tap.
  7. Switch to another tab and back, so vitals.js sends its report. Open vitals.ndjson and find the last INP line. Which part is the largest now?
Results from one run

These come from headless Chrome 157 on a 2019 laptop (Intel Core i7-9750H), through the DevTools Protocol, not the DevTools UI. Your numbers will differ.

  • Step 2: nine taps of 736–784 ms. Processing was the largest part, 357–391 ms.
  • Step 3: the snippet printed DIV#map.onclick (event-listener) 347 ms, function "" at seats.js:1525, and the fetch snippet returned 41.
  • Step 4: taps of 360–464 ms, processing 0–3 ms. The second frame’s invoker was Scheduler.yield.then (resolve-promise).
  • Step 5: taps of 744–848 ms, processing 356–413 ms, one frame with DIV#map.onclick.
  • Step 6: taps of 368–392 ms, one frame of 65–77 ms per tap, with no script listed.
  • Step 7: "value":392,"rating":"needs-improvement", input delay 93.7 ms, processing 28.5 ms, presentation delay 269.8 ms, totalPaintDuration 264.3 ms, and no script. Presentation delay is now the largest part. Processing is 28.5 ms here and 0–2 ms in step 6, because web-vitals starts it at pointerdown.

Stretch: with Fix 2 in place, make yieldToMain() always take the setTimeout branch by changing its if to if (false). Compare the invoker of the frame after the tap and the tap’s three parts.

Cheat sheet

Taps that feel frozen
  1. INP = input delay + processing duration + presentation delay; read the largest
  2. A change is on screen only after the task, its microtasks and rendering
  3. await of a resolved promise is a microtask: no frame in between
  4. Long animation frames name the script; name your handlers
  5. Change what the buyer waits for first, then yield
  6. scheduler.yield() continues before older tasks; setTimeout(0) waits behind them
  7. Remove work before you move it: update only what changed
  8. Every frame you add costs a full paint on this page
  9. A worker fits only when the work is long next to copying its data

Figure 12 is the whole module in one picture: which part of a slow interaction points where.

[slow interaction: INP and its three parts]
   |
   +-- input delay largest ------> work before the handlers: the frames
   |                               before it, hit testing, earlier handlers
   |                               -> make that work shorter or yield in it
   |
   +-- processing largest -------> the interaction's frame: scripts[] with
   |                               invoker, function and position
   |                               -> do less, change the screen first, yield
   |
   +-- presentation largest -----> after the handlers: rendering, and paint
                                   the frame entry does not attribute
                                   -> Module 6

Figure 12: the largest part names the frame to read and the kind of fix.

Next, in Module 6, Maya opens the 260 ms paint task that follows every tap. She also finds out why the map stutters when it scrolls, and why the Buy button jumps.

Sources