Back to results for “Event Loop & Concurrency”
JavaScript › Event Loop & Concurrency

How would you break a large synchronous task into chunks to keep the UI responsive?

Advanced

Answer

Split the work into smaller batches and yield control back to the event loop between them using setTimeout(fn, 0) or requestIdleCallback(), allowing pending UI updates and user input to be processed between chunks.
function processInChunks(items, chunkSize, fn) {
  let i = 0;
  function next() {
    const chunk = items.slice(i, i + chunkSize);
    chunk.forEach(fn);
    i += chunkSize;
    if (i < items.length) setTimeout(next, 0);
  }
  next();
}
Real-world example Processing 100,000 rows of imported CSV data client-side without freezing the browser tab.

Common follow-ups: How does requestIdleCallback differ from setTimeout for this purpose?