Advertisement
Advanced JavaScript, Event Loop & Concurrency

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

Short 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.

Save JavaScript mock interview
Advertisement
AModel 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.
Likely follow-ups
  • How does requestIdleCallback differ from setTimeout for this purpose?
Related topics