Course contentsShow
← Web Development
Lesson 2071 of 2,98238. JavaScript Performance in the BrowserFree lesson

Breaking Up Long Tasks with setTimeout

Splitting synchronous work into smaller chunks using setTimeout(fn, 0) to yield to the browser between operations.

Breaking Up Long Tasks with setTimeout

You'll learn how to split heavy synchronous work into smaller chunks using setTimeout to prevent blocking the main thread.


The Problem: Blocking Work

When you run a large synchronous operation—like processing thousands of array items or complex calculations—JavaScript executes it all at once. During that time, the browser can't respond to user clicks, render updates, or run other code. The page feels frozen.

The Solution: Yielding Control

By breaking your work into smaller pieces and using setTimeout(fn, 0) between them, you give the browser breathing room. Even though the delay is zero milliseconds, setTimeout schedules the next chunk to run after the browser handles other pending tasks like user input or rendering.

Analogy: Imagine washing 1,000 dishes. Doing them all without stopping exhausts you and prevents answering the doorbell. If you wash 50 dishes, take a quick break to check the door, then wash 50 more, you stay responsive.

How It Works

function processItems(items) {
  let index = 0;
  const chunkSize = 50;

  function processChunk() {
    const end = Math.min(index + chunkSize, items.length);
    
    for (let i = index; i < end; i++) {
      // Do heavy work with items[i]
    }
    
    index = end;
    
    if (index < items.length) {
      setTimeout(processChunk, 0); // Yield, then continue
    }
  }
  
  processChunk();
}

After processing 50 items, setTimeout schedules the next batch. The browser can handle clicks or repaints between chunks.

When to Use This

Use this technique when you have unavoidable synchronous work that takes more than 50ms. It won't make the total work faster, but it keeps the UI responsive.

Key Takeaway: setTimeout(fn, 0) lets you split long synchronous tasks into chunks that yield control back to the browser, preventing UI freezes and maintaining interactivity.