Full answer
JavaScript on the main thread shares time with rendering and input. Long computations freeze the page. A dedicated worker has its own event loop and thread. The two sides cannot share variables. They communicate by messages.
Basics:
- Create with
new Worker(url), or from a Blob URL for inline code. Modules can be loaded with{ type: 'module' }. worker.postMessage(data)sends data. The data is copied with the structured clone algorithm, so it can be objects, arrays, Maps and typed arrays, but not functions or DOM nodes.worker.onmessagereceives results. Handleonerrorandonmessageerror, and callworker.terminate()when it is not needed.- Large binary data can be transferred instead of copied:
postMessage(buffer, [buffer])moves anArrayBufferwithout a copy, and the sender then loses access to it.SharedArrayBufferallows shared memory, but it needs cross-origin isolation headers. - Inside a worker there is no
windowordocument. There arefetch, timers,IndexedDBandimportScripts(orimportin module workers).
Good uses: parsing big JSON or CSV, image or audio processing, encryption, diffing, search index building, and a heavy library that has no UI. Poor uses: tiny tasks, where the message cost is more than the work, and anything that needs the DOM.
Libraries such as Comlink wrap postMessage into promise-style calls. A pool of workers can use several cores. Service workers and shared workers are different kinds, with other lifecycles.
Practical points: build the worker with your bundler so the file is hashed and found. Check that CSP allows worker-src and blob: when you create Blob workers.
The page below starts a counter on the main thread with setInterval every 10 milliseconds, then sends 30 million loop steps to a worker. The counter keeps ticking while the worker computes. The test also runs the same loop on the main thread, where the counter does not tick.
<script>
const src = `onmessage = (e) => {
let sum = 0;
for (let i = 0; i < e.data; i++) sum += i % 3;
postMessage(sum);
};`;
const worker = new Worker(URL.createObjectURL(new Blob([src], { type: 'text/javascript' })));
let ticks = 0;
const timer = setInterval(() => { ticks += 1; }, 10);
window.result = new Promise((resolve) => {
worker.onmessage = (e) => { clearInterval(timer); resolve({ sum: e.data, ticks }); };
});
worker.postMessage(30000000);
</script>Run in headless Chrome 156 through Playwright. Two full runs gave the same results. The worker ran for about 1 second, and the main thread timer kept ticking about 90 to 100 times. The same loop on the main thread allowed no ticks. Exact numbers vary by machine.
Key points
- A worker is a separate thread with its own event loop and no DOM.
- Communicate with postMessage. Data is structured-cloned.
- Transfer large buffers to avoid copying.
- Use for CPU-heavy work, not tiny tasks or DOM work.
- Terminate workers and handle errors.
Common mistakes
- Expecting to share variables or call DOM functions from a worker.
- Sending huge objects back and forth in every frame.
- Creating a new worker for every small task.
- Forgetting error handling and termination.
Follow-ups
- What is the cost of structured cloning?
- When do you need SharedArrayBuffer?
- How does a worker differ from a service worker?
Tips
- State what a worker cannot do before what it can.
- Give one good use and one poor use.