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

Breaking Up Long Tasks

Techniques for splitting heavy computation into smaller chunks that yield control back to the browser.

Breaking Up Long Tasks

What you'll learn: How to split heavy JavaScript computations into smaller chunks so the browser stays responsive.

Why Break Up Long Tasks?

When JavaScript runs a task that takes more than 50ms, the browser can't respond to user input, scroll smoothly, or update the UI. The main thread is blocked—your page feels frozen.

Think of it like a grocery checkout line with one cashier handling one massive order. Everyone behind that customer must wait. If that big order was split into smaller transactions with breaks in between, other customers could be served too.

Techniques for Splitting Tasks

1. setTimeout with Zero Delay

Break work into chunks and yield control between them:

function processLargeArray(items) {
  let index = 0;
  
  function processChunk() {
    const chunkSize = 50;
    const end = Math.min(index + chunkSize, items.length);
    
    for (; index < end; index++) {
      // Process each item
      heavyComputation(items[index]);
    }
    
    if (index < items.length) {
      setTimeout(processChunk, 0); // Yield control
    }
  }
  
  processChunk();
}

Each setTimeout returns control to the event loop, letting the browser handle rendering and user interactions.

2. requestIdleCallback for Non-Urgent Work

function processWhenIdle(items) {
  let index = 0;
  
  function processChunk(deadline) {
    while (index < items.length && deadline.timeRemaining() > 0) {
      heavyComputation(items[index++]);
    }
    
    if (index < items.length) {
      requestIdleCallback(processChunk);
    }
  }
  
  requestIdleCallback(processChunk);
}

This processes work only when the browser is idle, perfect for background tasks.

When to Use This Pattern

  • Processing large datasets
  • Complex calculations
  • Heavy DOM updates
  • Any loop exceeding 50ms

Key Takeaway: Breaking long tasks into smaller chunks with setTimeout or requestIdleCallback keeps the main thread responsive, preventing UI freezes and maintaining a smooth user experience.