intermediate
Web Workers
Move CPU-heavy work off the main thread with message passing, structured cloning, transferables, and worker limits.
Web Workers run JavaScript away from the main thread, so CPU-heavy parsing, compression, search, or analysis does not block input and rendering. Communication happens through postMessage with structured cloning or transferables. Workers do not have DOM access, so UI work remains on the main thread.
const worker = new Worker('/search.worker.js');
worker.postMessage({ query, buffer }, [buffer]); // transferable avoids copy
worker.onmessage = (event) => renderResults(event.data.hits);
Startup and serialization overhead can exceed benefit for tiny tasks. Shared memory patterns need explicit synchronization and browser support checks.
On interviews: when workers help, why moving tiny work can hurt, and how transferables avoid copying large buffers.
Common pitfalls: workers do not fix slow DOM rendering. Serialization overhead can outweigh benefits for small tasks.
The trade-off is convenience versus control — pick the mechanism that matches your coupling and performance budget.
Checklist:
- Move CPU-bound work, not DOM updates.
- Use transferables for large ArrayBuffers.
- Terminate idle workers when appropriate.
- Measure end-to-end latency, not only CPU time.