Skip to content

Improving INP with scheduler.yield(): breaking up long tasks without slowing them down

How to fix a poor Interaction to Next Paint score: find which phase is slow, yield with scheduler.yield(), and avoid the setTimeout fallback's 4 ms penalty.

· 7 min read

  • Performance
  • Core Web Vitals
  • JavaScript

Interaction to Next Paint (INP) is the Core Web Vital that replaced First Input Delay. It measures how long a page takes to show a visual response after a click, tap or key press. Google rates it at the 75th percentile of real visits: 200 ms or less is good, over 500 ms is poor.

Most poor INP scores come from the same cause: JavaScript that keeps the main thread busy for hundreds of milliseconds, so the browser cannot paint. The standard fix is to break the work into pieces and let the browser in between. This article covers how to do that properly with scheduler.yield(), and the two mistakes that make it look fixed when it is not.

Every measurement below comes from a small test page run in headless Chromium 141 (via Playwright), using the browser’s own Event Timing data. The numbers will differ on your hardware. The relationships between them should hold.

Find out which part of the interaction is slow

An interaction has three phases, and the fix depends on which one is large:

  • Input delay: the time between the user’s input and the first event listener starting. This is usually the main thread being busy with something else.
  • Processing duration: the time your event listeners take to run.
  • Presentation delay: the time from the end of your listeners to the next frame being on screen. Style, layout, paint and requestAnimationFrame work all land here.

The web-vitals library reports all three through its attribution build. Version 6.2.3 exposes them as inputDelay, processingDuration and presentationDelay on the attribution object:

import { onINP } from "web-vitals/attribution";

onINP(({ value, attribution }) => {
  navigator.sendBeacon("/rum", JSON.stringify({
    inp: value,
    target: attribution.interactionTarget,
    inputDelay: attribution.inputDelay,
    processing: attribution.processingDuration,
    presentation: attribution.presentationDelay,
  }));
});

Collect this from real users, not only from your laptop. A large processingDuration means your own handler is the problem, which is what the rest of this article fixes. A large inputDelay means something else was already running, such as a timer, an analytics script or work started by an earlier interaction. A large presentationDelay usually points at expensive rendering, which yielding does not help.

The problem: one long task

A browser runs JavaScript on the same thread that handles input and paints. While a task runs, nothing else happens. Here is a click handler that does 400 ms of work, standing in for filtering a big list or rebuilding a table:

button.addEventListener("click", () => {
  status.textContent = "working";
  items.forEach(process); // 40 items, 10 ms each
  status.textContent = "done";
});

The browser cannot paint “working” because the handler has not returned. In our test, the click took about 400 ms to reach the next paint. The label did not even appear until the work was over.

The fix: yield between pieces of work

scheduler.yield() returns a promise that resolves in a later task. Awaiting it ends the current task, so the browser can handle input and paint, then resumes your function where it left off:

for (const item of items) {
  process(item);
  await scheduler.yield();
}

It differs from the old setTimeout(resolve, 0) trick in one important way. The continuation is queued ahead of other tasks waiting for the thread, rather than at the back. We tested this by queuing a setTimeout(…, 0) callback and then yielding:

  • After await new Promise(r => setTimeout(r, 0)), the other callback ran first and our code resumed second.
  • After await scheduler.yield(), our code resumed first and the other callback ran second.

So the continuation does not go to the back of the queue, and yielding costs you less when the page is busy. MDN documents that the continuation defaults to user-visible priority, and inherits the priority of an enclosing scheduler.postTask() callback.

Support, and a fallback that is slower than you think

scheduler.yield() shipped in Chrome 129 and Firefox 142. At the time of writing, MDN’s compatibility data lists Safari, including iOS, as unsupported. So you need a fallback:

const yieldToMain = () =>
  globalThis.scheduler?.yield
    ? scheduler.yield()
    : new Promise((resolve) => setTimeout(resolve, 0));

This works, but the fallback has a cost people forget. Browsers clamp nested timers: once setTimeout calls are nested more than five deep, the HTML specification says each is delayed by at least 4 ms. A loop that awaits a fresh setTimeout each time is exactly that. We measured the cost of one yield, in a page with nothing else going on:

Yield method Cost per yield
scheduler.yield() about 0.004 ms
setTimeout(resolve, 0) about 4 ms

So yielding after every item is cheap with one and ruinous with the other. We ran 400 items of 1 ms work each:

Strategy Total time
No yielding 400 ms
Yield after every item, scheduler.yield() 404 ms
Yield after every item, setTimeout 2,020 ms

The same code was five times slower in the fallback path, which is what Safari and older Chrome and Firefox versions take. The answer is not to avoid yielding, but to yield by time budget rather than by count.

Yield by time budget, not after every item

The browser only needs a gap every few dozen milliseconds. The Long Tasks API treats anything over 50 ms as long, so a budget of about 40 ms keeps tasks close to that line. A task lasts the budget plus one item of work, so use a smaller budget if your items are slow:

async function processInChunks(items, work, budgetMs = 40) {
  let last = performance.now();
  for (const item of items) {
    if (performance.now() - last > budgetMs) {
      await yieldToMain();
      last = performance.now();
    }
    work(item);
  }
}

With the same 400 items, this took 401 ms using scheduler.yield() and 414 ms using the setTimeout fallback. The fallback now pays its 4 ms about ten times instead of 400 times. The total stays close to the unyielded time, but the page can respond throughout.

Mistake one: yielding once, at the top

A common fix is a single await at the start of the handler, so the click gets its visual feedback:

button.addEventListener("click", async () => {
  status.textContent = "working";
  await yieldToMain();
  items.forEach(process); // still one 400 ms block
  status.textContent = "done";
});

This does fix the interaction it is in. The click’s duration dropped from about 400 ms to 16 ms, because the browser painted “working” before the heavy work began. If this is the only interaction you test, INP looks solved.

But the 400 ms block still exists, just later. To see what that does, we sent a second click 150 ms after the first. With the single yield, the second click waited roughly 250 to 280 ms before its listener could start, and took about as long to reach a paint. With yielding in the loop, the same second click started its listener after about 1 to 3 ms.

Moving the work to after the first yield moves the problem onto whatever the user does next. INP is close to the worst interaction on the page, so it will find that one.

Mistake two: assuming nothing changes while you yield

Yielding lets the browser in, but it also lets everything else in. After await, the state your code assumed may have changed: the user may have clicked again, navigated, or edited the input you are filtering. A handler that yields in a loop should be written as if it can be re-entered.

If the handler runs again while an earlier run is paused, the two interleave, which is rarely what you want. Guard against it with a run counter:

let run = 0;

async function filter(query) {
  const mine = ++run;
  const results = [];
  for (const item of items) {
    if (mine !== run) return; // a newer query started, abandon this one
    if (matches(item, query)) results.push(item);
    // in real code, yield here on a time budget (keep `last` outside the loop), as in processInChunks()
  }
  render(results);
}

Also keep the cheap, visible part of the response before the first yield. Update the pressed state, show the spinner, then yield. Anything the user needs to see to know their click registered belongs ahead of the await.

What yielding does not fix

Yielding splits JavaScript. It does not shrink it. If the real cost is something else, look elsewhere:

  • Large presentation delay: too much DOM, expensive CSS selectors, or forced layout. Render less (virtualise long lists, or use content-visibility: auto on off-screen sections) rather than chunking the same render.
  • Large input delay on load: the bundle is still executing when users start clicking. Ship less JavaScript, and defer what is not needed for the first interactions. Our Astro site write-up covers one way to keep the JavaScript to almost nothing.
  • Work that does not touch the DOM: parsing, sorting or searching a large dataset belongs in a Web Worker, where it cannot block input at all. Yielding is the right tool when the work needs the main thread.

A checklist

  1. Measure INP with attribution in the field. Find the phase that is large.
  2. For large processing duration, show feedback first, then split the work.
  3. Yield on a time budget of around 40 ms, not after every item.
  4. Feature-detect scheduler.yield() and fall back to setTimeout.
  5. Make yielding code safe to re-enter.
  6. Test two quick interactions in a row, not just one.

If your site feels slow to use, or your Core Web Vitals report is red, we can find what is blocking the main thread and fix it. See our web development service.

Have something you'd like built?

Tell us what you're building. We'll reply within two working days with questions, an approach and next steps.

Start a project
Esc

↑ ↓ to move · Enter to open