Improving INP: Break Up the Work Behind a Click

Improving INP: Break Up the Work Behind a Click

Click and nothing happens, and then it happens, this feeling is what INP is counting, we wanted to see it on our own screen, so we made one page with three buttons, and every button does a dumb loop which keeps the processor busy 300 ms.

The first one is written how most of us write, put text Saving, do the heavy thing, put text Done. We clicked it, and the observer wrote 336 ms. But what we saw with eyes is more interesting, Saving did not appear at all! The page just waited and showed Done, because browser had no free moment for drawing between our two lines.

In the second button we added one line, await scheduler.yield, after the Saving text. 56 ms. The third button does it the old way, requestAnimationFrame and inside it setTimeout, and also 56 ms. We want to say it clear, the loop is not faster, it is the same 300 ms in all three, only in two of them the browser could paint first, and the person got an answer on the click.

async function yieldToMain() {
  if ('scheduler' in window && 'yield' in scheduler) {
    return scheduler.yield();
  }
  return new Promise((resolve) => setTimeout(resolve, 0));
}

button.addEventListener('click', async () => {
  button.classList.add('is-added');
  await yieldToMain();
  saveCart();
  await yieldToMain();
  trackAddToCart();
});

Some browsers don't have scheduler.yield yet, so in the code lower we ask is it there and otherwise use setTimeout. And we have not tried this on a cheap phone, there we expect the numbers to be much worse, but expecting is not measuring, web-vitals on real visitors will tell.

async function filterRows(rows, matches) {
  const visible = [];
  let lastYield = performance.now();

  for (const row of rows) {
    if (matches(row)) visible.push(row);
    if (performance.now() - lastYield > 50) {
      await yieldToMain();
      lastYield = performance.now();
    }
  }
  return visible;
}
import { onINP } from 'web-vitals/attribution';

onINP(({ value, attribution }) => {
  console.log(value, attribution.interactionTarget, {
    inputDelay: attribution.inputDelay,
    processing: attribution.processingDuration,
    presentation: attribution.presentationDelay,
  });
});

See also: React performance optimization and a budget.