Sub topic 16
Keeping Your App Responsive
This chapter assumes you know how tasks, microtasks, and rendering steps share one thread, and why a long synchronous loop freezes a page. You have two main tools against that problem. You can break the work into pieces, or you can move it off the main thread.
Chunking: Give the Loop a Turn
The event loop can only handle a click, run a timer, or paint a frame between tasks. If your work runs as one 2-second task, nothing else happens for 2 seconds. When you split the work into many short tasks, the loop gets a chance to handle other work between each chunk.
An async function with a yield helper is an easy way to write this:
function yieldToLoop() {
return new Promise((resolve) => setTimeout(resolve, 0));
}
async function sumSquares(items, chunkSize = 5000) {
let total = 0;
for (let i = 0; i < items.length; i++) {
total += items[i] * items[i];
if (i > 0 && i % chunkSize === 0) {
await yieldToLoop(); // let input and rendering run
}
}
return total;
}
const data = Array.from({ length: 200000 }, (_, i) => i);
sumSquares(data).then((total) => console.log('total:', total));
console.log('started; the page stays usable');The yield has to schedule a task, such as a timer. A resolved promise only schedules a microtask, and the loop drains every microtask before it renders or reads input.
Pick a chunk size that keeps each chunk well under about 50 ms. Browsers treat any task longer than 50 ms as a "long task", and users start to notice the lag at that point. Nested setTimeout calls can be clamped to a 4 ms minimum delay after a few levels of nesting. That clamping makes many tiny chunks slower overall, so make your chunks as large as you can while still staying responsive.
Web Workers: A Second Thread
Some work can't be split up easily, or it would take too long even when chunked. A Web Worker runs a script on a separate thread with its own event loop. A worker has no access to the DOM. It talks to the main thread by passing messages, and each message arrives as a task on the other side's task queue.
You can paste this into the console of a simple page such as about:blank. Strict Content Security Policies can block workers created from blobs.
const workerSource = `
self.onmessage = (event) => {
let sum = 0;
for (let i = 0; i < event.data; i++) sum += i;
self.postMessage(sum);
};
`;
const blob = new Blob([workerSource], { type: 'text/javascript' });
const worker = new Worker(URL.createObjectURL(blob));
worker.onmessage = (event) => {
console.log('sum from worker:', event.data);
worker.terminate();
};
worker.postMessage(1e9);
console.log('main thread is still free');Messages are copied with the structured clone algorithm. Sending large objects therefore has a cost of its own. You can transfer an ArrayBuffer instead of copying it, which avoids most of that cost. In Node.js, the worker_threads module plays the same role as Web Workers.
Choosing an Approach
| Situation | Use |
|---|---|
| Work needs the DOM, or is easy to split | Chunking with task yields |
| Heavy CPU work that is pure computation | Web Worker or `worker_threads` |
| Visual updates spread across frames | `requestAnimationFrame` per chunk |
| Node.js server handling a CPU-heavy request | `worker_threads`, so other requests keep being served |
Exercise
A developer chunks a long loop with await Promise.resolve() between chunks, but the page still freezes until the loop ends. Why, and what is the fix?
Show answer
Each await on a resolved promise schedules its continuation as a microtask. The loop drains the whole microtask queue before it renders or handles input, so the chunks still run back to back. The fix is to yield with a task, for example await new Promise(r => setTimeout(r, 0)), or to move the work to a Web Worker.
Exercise
Why can't a Web Worker update a progress bar directly, and how should it report progress?
Show answer
Workers have no access to the DOM. The worker should call postMessage with progress values, and the main thread's onmessage handler should update the progress bar.