Breaking Up Long-Running JavaScript with setTimeout
You'll learn how to split heavy synchronous JavaScript into smaller chunks so the browser can stay responsive.
The Problem with Long-Running Scripts
When JavaScript executes a long synchronous task (like processing thousands of array items or complex calculations), it monopolizes the main thread. The browser can't respond to user clicks, update the UI, or even scroll smoothly—everything freezes until your script finishes.
You already learned to identify long tasks. Now you'll learn to fix them.
The setTimeout Solution
setTimeout lets you voluntarily pause your work and give control back to the browser, even with a delay of zero milliseconds:
function processHugeArray(items) {
let index = 0;
function processChunk() {
// Process a small batch (e.g., 50 items)
const endIndex = Math.min(index + 50, items.length);
for (let i = index; i < endIndex; i++) {
// Do expensive work on items[i]
doExpensiveWork(items[i]);
}
index = endIndex;
// If more items remain, schedule next chunk
if (index < items.length) {
setTimeout(processChunk, 0);
}
}
processChunk(); // Start processing
}
Even setTimeout(..., 0) yields control. The browser can render, respond to input, then come back to your next chunk.
Think of It Like This
Imagine eating a huge meal in one sitting versus taking breaks between courses. Breaking up work lets the browser "digest" rendering updates and user interactions between your processing chunks.
When to Use This Pattern
Use chunking for CPU-intensive loops that don't need immediate completion: data processing, search indexing, canvas rendering, or generating reports.
Key Takeaway: Use setTimeout to break synchronous JavaScript into smaller chunks, yielding control back to the browser so it can remain responsive and avoid long tasks that block rendering and interaction.