← Back to Frontend, page 1

frontend-0010 · Medium mid

A script must process 200,000 rows in the browser. How do you keep the page responsive while it runs?

JavaScript runs on the main thread, so one long loop blocks painting and input. Split the work into small chunks and yield between them with setTimeout, scheduler.yield or a MessageChannel, or move the work to a Web Worker.

Full answer

The browser runs JavaScript, style, layout and painting on one main thread. A task that runs for 500 milliseconds blocks all three. Clicks wait, animations stop, and INP gets worse. Any task over 50 milliseconds is called a long task.

There are three common ways to keep the page responsive.

  1. Chunking. Process a fixed number of rows, then give control back to the event loop so that input and painting can run, then continue. A time budget works better than a fixed count, because slow devices take longer per row. Check performance.now() and yield after about 10 to 16 milliseconds.
  2. Scheduling APIs. scheduler.yield() continues your work with a high priority after the browser has handled pending input. requestIdleCallback runs work only when the browser is idle, which suits low priority jobs, but it can be delayed for a long time on a busy page.
  3. A Web Worker. If the work does not need the DOM, move it to another thread. The main thread then has nothing to block.

The snippet below sums 200,000 numbers in chunks with a 10 millisecond budget. It yields with setTimeout, which has a minimum delay in some cases, and works everywhere. The test starts the job and measures the longest block of the main thread with the long task observer. Chunked processing finishes with no long task, while the same loop in one piece creates one.

Chunking makes the total time a bit longer because of the yields, but the page stays usable. When the user can leave or change the input, add a cancel check at each yield point, so that old work does not keep running.

html
<script>
  const rows = Array.from({ length: 200000 }, (_, i) => i);
  const tick = () => new Promise((r) => setTimeout(r, 0));
  async function sumInChunks(list, budgetMs = 10) {
    let total = 0, start = performance.now();
    for (let i = 0; i < list.length; i++) {
      total += list[i] % 7;
      if (performance.now() - start > budgetMs) { await tick(); start = performance.now(); }
    }
    return total;
  }
  window.longTasks = 0;
  new PerformanceObserver((l) => { longTasks += l.getEntries().length; }).observe({ type: 'longtask' });
  window.done = sumInChunks(rows);
</script>

Run in headless Chrome 156 through Playwright. Two full runs gave the same results. Checked in headless Chrome: the chunked result equals the plain loop result, and the long task observer saw no task above 50 milliseconds. Results on slower devices were not measured.

Key points

  • One long task blocks input, painting and animation.
  • Chunk the work and yield with a time budget, not a fixed count.
  • scheduler.yield and setTimeout are yield points. requestIdleCallback is for low priority work.
  • A Web Worker is the best option when the work does not need the DOM.
  • Add cancellation so that stale work stops.

Common mistakes

  • Using a Promise.resolve loop to yield. Microtasks run before painting, so the page still freezes.
  • Choosing a fixed chunk size that is fine on a laptop and too big on a low-end phone.
  • Updating the DOM for every row inside the loop.
  • Forgetting to cancel the job when the user starts a new one.

Follow-ups

  • Why does await Promise.resolve() not unblock painting?
  • When is requestIdleCallback a bad choice?
  • How would you report progress without slowing the job down?

Tips

  • Mention the 50 millisecond long task definition.
  • Offer the worker as the next step before the interviewer asks.