← Back to JavaScript, page 3

javascript-0044 · Hard senior

How do you keep an application responsive while processing a large amount of data in JavaScript?

Long synchronous work blocks the single main thread, so timers, input, and rendering wait. Fix it by splitting the work into small chunks and yielding to the event loop between them, moving heavy computation to a Web Worker or worker thread, or reducing the work with better algorithms and data structures. Measure first with the performance tools.

Full answer

Because JavaScript runs on one thread, a loop that takes 500 ms freezes the page for 500 ms. Clicks are not handled, animations stop, and timers fire late. A browser aims to produce a frame every 16 ms, and responsiveness metrics such as Interaction to Next Paint penalize long tasks, which are tasks over 50 ms.

The options, from cheapest to most involved:

  1. Do less work. Use a better algorithm, avoid repeated array scans, debounce triggers, or use virtualized lists so only visible rows are processed.
  2. Chunk the work. Process a slice of items, then yield to the event loop so other tasks can run, then continue. Yielding must use a macrotask (setTimeout, MessageChannel, or scheduler.yield() where available). A promise microtask does not help, because the microtask queue is drained before the event loop moves on.
  3. Move the work off the main thread. A Web Worker (browser) or worker_threads (Node.js) runs code in a separate thread. Data is copied with structured cloning or transferred without copying for ArrayBuffer. Workers have no DOM access.
  4. Schedule low-priority work with requestIdleCallback when it can wait.

Choose chunking when the work needs the DOM or must be simple to ship. Choose a worker for heavy pure computation such as parsing, image processing, or sorting a large data set.

Always measure with the Performance panel, and look for long tasks before changing code.

javascript
const items = Array.from({ length: 200 }, (_, i) => i + 1);
const log = [];

function heavy(n) {
  let total = 0;
  for (let i = 0; i < 50000; i++) total += (n * i) % 7;
  return total;
}

function processAllAtOnce() {
  let sum = 0;
  for (const item of items) sum += heavy(item);
  log.push('blocking run finished');
  return sum;
}

const yieldToEventLoop = () => new Promise((resolve) => setTimeout(resolve, 0));

async function processInChunks(chunkSize) {
  let sum = 0;
  for (let start = 0; start < items.length; start += chunkSize) {
    for (const item of items.slice(start, start + chunkSize)) sum += heavy(item);
    log.push(`chunk ${start / chunkSize + 1} done`);
    await yieldToEventLoop();
  }
  return sum;
}

(async () => {
  setTimeout(() => log.push('timer fired'), 0);
  const blockingSum = processAllAtOnce();
  await yieldToEventLoop();
  console.log('blocking order:', log.join(' | '));

  log.length = 0;
  setTimeout(() => log.push('timer fired'), 0);
  const chunkedSum = await processInChunks(100);
  console.log('chunked order:', log.join(' | '));
  console.log('same result:', blockingSum === chunkedSum);
})();

Run with Node.js v24.22.1 as js-44.js; two runs gave identical output. Output: blocking order: blocking run finished | timer fired chunked order: chunk 1 done | timer fired | chunk 2 done same result: true

Key points

  • Long synchronous tasks block timers, input, and rendering.
  • Yield with a macrotask between chunks; a microtask does not let other tasks run.
  • Web Workers and worker threads move computation off the main thread but cannot touch the DOM.
  • Reduce work first with better algorithms and virtualization.
  • Measure long tasks (over 50 ms) before optimizing.

Common mistakes

  • Yielding with await Promise.resolve(), which only schedules a microtask and does not let timers, input, or rendering run.
  • Chunking too small, so scheduling overhead dominates, or too large, so each chunk is itself a long task.
  • Sending huge objects to a worker with copying instead of transferring buffers.
  • Optimizing without profiling and moving the wrong work.

Follow-ups

  • How would you show a progress indicator while a worker processes a file?
  • What is the difference between requestAnimationFrame and requestIdleCallback?
  • How does scheduler.yield differ from setTimeout for yielding?

Tips

  • Start by naming the symptom: long tasks over 50 ms. It shows you know how to measure.
  • Explain why a microtask is not a valid yield point.
  • Offer two or three options and say how you would choose between them.