CodeZettaInterview Hub

JavaScript · Browser APIs · Senior · Architecture

When should you use Web Workers, and what are their limitations?

Short Interview Answer

Use workers for CPU-heavy JS off the main thread; they can't touch the DOM and communicate via messaging/structured clone or SharedArrayBuffer.

Detailed Explanation

Workers have their own event loop and global scope. Great for parsing, encryption, image processing, search indexes. Limitations: no DOM access, data copy costs (unless transferable/SAB with care), debugging complexity, and duplicate module memory. Dedicated vs shared vs service workers serve different roles — service workers are for network proxying/offline, not general CPU offload. Design clear message protocols and timeouts. Measure whether transfer overhead dominates.

Example

const worker = new Worker(new URL('./heavy.js', import.meta.url), { type: 'module' });
worker.postMessage({ type: 'run', payload });
worker.onmessage = (e) => console.log(e.data);

Interview Tip

Distinguish service workers from compute workers.

Common Mistake

Trying to update the DOM directly from a worker.

Did you know this answer?