What is a Worker Thread?
Workers let JavaScript run code in parallel on separate threads: Web Workers in browsers and worker_threads in Node.js; each worker has its own event loop and memory, and communicates with the main thread by passing messages.
Why they exist
JavaScript on the main thread is single-threaded. CPU-heavy work (image processing, parsing large files, encryption, data crunching, syntax highlighting) blocks the UI, hurting responsiveness (INP). Moving it to a worker keeps the page smooth.
How they communicate
worker.postMessage(data)/self.onmessage(browser), orparentPort(Node).- Data is structured-cloned (copied) by default.
- Transferables (
ArrayBuffer,MessagePort,ImageBitmap,OffscreenCanvas) can be moved without copying: ownership transfers to the worker. SharedArrayBufferlets threads share memory directly (withAtomicsfor coordination).
Limitations
- No DOM access in workers (no
document, nowindow). They do havefetch, timers,IndexedDB, WebSockets,OffscreenCanvasand more. - Startup cost and memory overhead: reuse workers (a pool) rather than creating one per task.
- Messaging has overhead; send work in reasonably large chunks.
Types of browser workers
- Dedicated workers: one page.
- Shared workers: shared between tabs of the same origin.
- Service workers: network proxy for offline support, caching and push, not for general computation.
Libraries
Comlink makes workers feel like calling async functions. Bundlers (Vite, webpack, Next.js) support new Worker(new URL("./worker.js", import.meta.url)).
Code example
1// A Web Worker created from inline code (normally it would be its own file)2const workerSource = `3 self.onmessage = (event) => {4 const { numbers } = event.data;5 // CPU-heavy work runs here without freezing the page6 let primes = 0;7 for (const n of numbers) {8 let isPrime = n > 1;9 for (let d = 2; d * d <= n; d++) if (n % d === 0) { isPrime = false; break; }10 if (isPrime) primes++;11 }12 self.postMessage({ primes });13 };14`;15const url = URL.createObjectURL(new Blob([workerSource], { type: "text/javascript" }));16const worker = new Worker(url);1718// Wrap the message exchange in a promise19const runInWorker = (data) =>20 new Promise((resolve, reject) => {21 worker.onmessage = (e) => resolve(e.data);22 worker.onerror = (e) => reject(e);23 worker.postMessage(data);24 });2526const numbers = Array.from({ length: 200_000 }, (_, i) => i);27const started = performance.now();28const ticker = setInterval(() => {}, 16); // the main thread stays free to run this29const { primes } = await runInWorker({ numbers });30clearInterval(ticker);31console.log(`${primes} primes found off the main thread in ${(performance.now() - started).toFixed(0)}ms`); // 17984 primes ...3233worker.terminate();34URL.revokeObjectURL(url);3536// Node.js equivalent:37// import { Worker } from "node:worker_threads";38// const w = new Worker("./prime-worker.js", { workerData: numbers });
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.