Sub topic 16
Keeping Your App Responsive
This chapter assumes you understand the task queue, the microtask queue, the rendering steps from earlier chapters, and how a long task blocks the loop. You should also be comfortable with promises and async/await. Here the question shifts from diagnosis to repair. When you have a large amount of work to do, how do you get it done without freezing the page or stalling a server?
There are two strategies:
- Yield: split the work into pieces and give the event loop a turn between pieces. The work still runs on the main thread.
- Offload: move the work to another thread, so the main thread never runs it at all.
Why Yielding Works
The browser can only process input, run rendering steps, or start other tasks between tasks. A single task that runs for 2 seconds means 2 seconds with no clicks handled and no frames painted. If you split that work into 200 tasks of 10 ms each, the total CPU time is about the same, but the loop gets 200 chances to do other things. Users perceive delays of about 100 ms as lag. At 60 frames per second a frame lasts about 16.7 ms, so a common target is to keep each chunk under roughly 10 ms.
Chunking by Count
The simplest version processes a fixed number of items, then schedules the rest as a new task:
function processInChunks(items, handle, chunkSize = 1000) {
let index = 0;
function nextChunk() {
const end = Math.min(index + chunkSize, items.length);
for (; index < end; index++) {
handle(items[index]);
}
if (index < items.length) {
setTimeout(nextChunk, 0);
}
}
nextChunk();
}
processInChunks(Array.from({ length: 100000 }, (_, i) => i), (n) => n * n);This approach has a weakness. The right chunkSize depends on how expensive handle is and how fast the device is. A size of 1000 items may take 2 ms on a desktop and 40 ms on a low-end phone.
Chunking by Time Budget
A more reliable approach measures elapsed time and yields when the budget runs out. The version below also uses async/await, so the loop reads like ordinary code.
function yieldToMain() {
if (globalThis.scheduler && typeof globalThis.scheduler.yield === 'function') {
return globalThis.scheduler.yield();
}
return new Promise((resolve) => setTimeout(resolve, 0));
}
async function processWithBudget(items, handle, budgetMs = 8) {
let deadline = performance.now() + budgetMs;
for (let i = 0; i < items.length; i++) {
handle(items[i]);
if (performance.now() >= deadline) {
await yieldToMain();
deadline = performance.now() + budgetMs;
}
}
}
const data = Array.from({ length: 1_000_000 }, (_, i) => i);
let sum = 0;
processWithBudget(data, (n) => { sum += Math.sqrt(n); })
.then(() => console.log('done, sum =', Math.round(sum)));This runs in both browsers and Node.js, because performance.now() is global in both. Two details matter here:
- The
awaitgives up control only because the promise it waits on is resolved by a task (setTimeout). The continuation therefore starts in a later task, after the loop has had a chance to render and handle input. scheduler.yield()is a newer browser API, first shipped in Chromium-based browsers. Its continuation is scheduled ahead of other queued tasks of similar priority, so your job does not lose its place behind unrelated work. The feature check makes the fallback automatic.
The setTimeout Clamp
Browsers clamp nested timers. Once setTimeout calls nest more than five levels deep, the minimum delay becomes about 4 ms. A chunked job with 500 chunks can lose around 2 seconds just waiting. Here are the common workarounds and their trade-offs:
| Yield mechanism | Is it a task? | Clamped? | Notes |
|---|---|---|---|
| `setTimeout(fn, 0)` | Yes | Yes, about 4 ms after nesting | Works everywhere, the simplest choice |
| `MessageChannel` postMessage | Yes | No | Fast. Older schedulers in libraries used this technique |
| `scheduler.yield()` | Yes (a prioritized continuation) | No | Keeps priority; needs a feature check |
| `requestIdleCallback` | Yes | Runs only when idle | Good for low-priority work; may be delayed a long time |
| `setImmediate` (Node.js) | Yes (check phase) | No | The idiomatic way to yield in Node.js |
| `Promise.resolve().then` | No (a microtask) | Not applicable | Does not yield |
A MessageChannel-based yield looks like this:
function yieldViaMessage() {
return new Promise((resolve) => {
const { port1, port2 } = new MessageChannel();
port1.onmessage = () => {
port1.close();
resolve();
};
port2.postMessage(null);
});
}Offloading to Web Workers
Chunking still spends main-thread time. If the work is pure computation, such as parsing a large file, image processing, or search indexing, a Web Worker runs it on a separate thread with its own event loop. Workers have no DOM access. They communicate with the page only by passing messages.
worker.js:
self.onmessage = (event) => {
const { numbers } = event.data;
let sum = 0;
for (const n of numbers) {
sum += Math.sqrt(n);
}
self.postMessage({ sum });
};main.js (loaded by a page served over HTTP, not from file://):
const worker = new Worker('worker.js');
worker.onmessage = (event) => {
console.log('worker result:', Math.round(event.data.sum));
};
worker.onerror = (event) => {
console.error('worker failed:', event.message);
};
const numbers = new Float64Array(5_000_000).map((_, i) => i);
worker.postMessage({ numbers }, [numbers.buffer]);
console.log('main thread is free while the worker computes');The second argument to postMessage is a transfer list. Without it, the browser copies the data with the structured clone algorithm, and copying a 40 MB array is itself a long task on the main thread. Transferring moves ownership of the ArrayBuffer instead, so the operation is close to instant. After the transfer, numbers is detached and has length 0 on the main thread.
The Node.js Equivalent: worker_threads
In Node.js, one CPU-heavy request blocks every other request on the server. The worker_threads module plays the role that Web Workers play in the browser. This single file acts as both the main thread and the worker:
const { Worker, isMainThread, parentPort, workerData } = require('node:worker_threads');
if (isMainThread) {
const worker = new Worker(__filename, { workerData: { limit: 50_000_000 } });
worker.on('message', (sum) => console.log('sum:', sum));
worker.on('error', (err) => console.error(err));
setInterval(() => console.log('main loop still ticking'), 100).unref();
} else {
let sum = 0;
for (let i = 0; i < workerData.limit; i++) sum += i % 7;
parentPort.postMessage(sum);
}While the worker runs, the interval keeps logging, which shows that the main loop stays free. Calling .unref() lets the process exit once the worker finishes. For work that arrives with each request, use a pool of workers instead of starting a new one per request, because each worker costs memory and startup time. Libraries such as Piscina provide ready-made pools.
Failure Modes and Gotchas
- Chunked state can change underneath you. Other code runs between chunks. If a user edits the list you are iterating over, you can get inconsistent results. Snapshot the input, or cancel and restart the job when the input changes.
- Cancellation. A long chunked job should check a flag or an
AbortSignalat each yield point. A worker can be stopped withworker.terminate(). - Worker startup and messaging cost. Starting a worker takes milliseconds, and cloning large objects costs time. For many small jobs, that overhead can exceed the work itself.
- Not all slowness is CPU. Layout thrashing (alternating DOM reads and writes) and very large DOM updates are main-thread rendering costs that workers cannot take over. Batch DOM writes, and use
requestAnimationFramefor visual updates. - Measure first. Use the Performance panel's long-task markers in your browser's developer tools, or
PerformanceObserverwithentryTypes: ['longtask'], to find the real problem before you restructure code.
Exercise
A developer "chunks" a 2-second loop by putting await Promise.resolve() after every 1000 items in an async function. The page still freezes for 2 seconds. Why, and what is the smallest fix?
Show answer
Each await Promise.resolve() schedules the continuation as a microtask. The microtask queue is drained completely before the event loop can render or handle input, so the whole job still behaves like one long task. The smallest fix is to await a promise resolved by a task, for example await new Promise(r => setTimeout(r, 0)), or scheduler.yield() where it is available.
Exercise
A worker receives a 200 MB ArrayBuffer through worker.postMessage({ buf }), and the main thread stalls for about 300 ms when the message is sent. What causes the stall, and how do you remove it? What side effect does your fix have?
Show answer
Without a transfer list, the data is copied with structured clone on the main thread, and copying 200 MB takes a long time. Pass the buffer in the transfer list: worker.postMessage({ buf }, [buf]). Ownership then moves to the worker with no copy. The side effect is that buf becomes detached on the main thread (its byteLength is 0), so the main thread can no longer use it.
Exercise
In a Node.js HTTP server, one route hashes a large file synchronously, and other requests time out while it runs. Name two fixes and say when you would choose each.
Show answer
The first fix is to move the hashing into a worker_threads worker, or better, a worker pool. This is the right choice for CPU-bound work, because it keeps the main loop completely free and can use multiple cores. The second fix is to process the file in chunks with a yield between them (for example, a stream that you hash incrementally, or setImmediate between pieces). This works when the job is moderate and you want to avoid worker overhead, but it still spends main-thread time and only interleaves the work with other requests.