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

setTimeout for Yielding

Using setTimeout(fn, 0) to defer work and allow the browser to handle user input and rendering.

setTimeout for Yielding

What you'll learn: How to use setTimeout(fn, 0) to voluntarily yield control back to the browser during long-running tasks.

The Core Problem

When JavaScript runs continuously for too long, it monopolizes the main thread. This blocks the browser from responding to user clicks, scrolling, or rendering updates—creating a frozen, unresponsive experience.

How setTimeout Yields Control

The setTimeout(fn, 0) pattern intentionally breaks your work into smaller chunks and schedules the next chunk to run after the current task completes. Even with a delay of 0 milliseconds, this doesn't mean "run immediately." Instead, it means "add this to the task queue and run it when the main thread is free."

The key: Between these scheduled chunks, the browser gets opportunities to handle user input and update the screen.

Simple Example

function processLargeArray(items) {
  let index = 0;
  
  function processChunk() {
    // Process 50 items at a time
    const endIndex = Math.min(index + 50, items.length);
    
    for (; index < endIndex; index++) {
      // Do expensive work with items[index]
      console.log(`Processing item ${index}`);
    }
    
    if (index < items.length) {
      // Yield to the browser, then continue
      setTimeout(processChunk, 0);
    }
  }
  
  processChunk();
}

The Analogy

Think of it like reading a long book to someone. Instead of reading all 500 pages without pause (blocking), you read one chapter, take a breath, check if they need anything (yield), then continue with the next chapter. The listener can interact with you between chapters.

Key Takeaway: Using setTimeout(fn, 0) creates breathing room for the browser by voluntarily yielding the main thread, keeping your UI responsive even during heavy JavaScript work.