Sub topic 13
Moving Work Off the Main Thread
This chapter assumes you have read the earlier chapters on the event loop and on ES modules. You should know that each runtime runs your JavaScript on a single thread, that callbacks wait in task and microtask queues, and how import and import.meta.url work. You also need a local web server for the browser examples, because browsers will not start workers from file:// pages.
Why a long loop freezes everything
The event loop can only take the next task once the current one finishes. Suppose a click handler runs a loop for two seconds. During those two seconds the browser cannot repaint, respond to input, or run timers. In Node.js the effect is just as bad. A server that is busy summing numbers cannot accept connections, read sockets, or fire setTimeout callbacks.
Promises do not fix this. Wrapping CPU-bound work in async or new Promise only changes when the work starts. It still runs on the same thread, and it still blocks that thread. The fix is a second thread with its own event loop. Browsers provide Web Workers for this, and Node.js provides the worker_threads module.
The worker model
A worker is a separate JavaScript environment running on its own operating system thread. It has its own global object, its own module graph, its own event loop, and its own heap. By default the main thread and the worker share no JavaScript objects. They talk only by sending messages.
Every message is copied with the structured clone algorithm. This algorithm handles primitives, plain objects, arrays, Map, Set, Date, RegExp, typed arrays, ArrayBuffer, and Error. It cannot copy functions, DOM nodes, or class instances along with their prototypes. A class instance arrives as a plain object, and its methods are gone.
Web Workers in the browser
The main script creates a worker from a script URL, sends it input, and listens for the result.
// main.js (browser)
const worker = new Worker('worker.js');
worker.onmessage = (event) => console.log('sum:', event.data);
worker.postMessage(10_000_000);Inside the worker, self refers to the worker's global object, which is a DedicatedWorkerGlobalScope. It receives messages and posts results back.
// worker.js
self.onmessage = (event) => {
let sum = 0;
for (let i = 0; i < event.data; i++) sum += i;
self.postMessage(sum);
};The page logs sum: 49999995000000. While the loop runs, the page still scrolls and responds to clicks.
The worker has many web APIs, including fetch, setTimeout, IndexedDB, WebSocket, crypto, and importScripts for classic workers. It has no document and no window, and it cannot touch the DOM. Any change to the page has to happen on the main thread after the worker sends its result back.
Module workers
If you pass type: 'module', the worker script is loaded as an ES module. It can then use import, and you no longer need importScripts.
// main.js (browser)
const worker = new Worker(new URL('./worker.mjs', import.meta.url), {
type: 'module',
});
worker.onmessage = (event) => console.log('sum:', event.data);
worker.onerror = (event) => console.error('worker failed:', event.message);
worker.postMessage(10_000_000);Resolving the path against import.meta.url makes it relative to the current module, not to the page. Bundlers also recognize this exact pattern and emit the worker as its own file.
Errors and shutdown
An exception the worker does not catch fires an error event on the Worker object. If you never listen for it, the failure shows up only in the console, and the main thread waits for a message that will never arrive. Call worker.terminate() from the main thread, or self.close() from inside the worker, once you are done with it. An idle worker that nobody terminates keeps its thread and memory.
worker_threads in Node.js
Node.js uses the same model with a different API. The worker gets its input through the workerData option, which is cloned once when the worker starts. It sends results back through parentPort.
// main.mjs (Node.js)
import { Worker } from 'node:worker_threads';
const worker = new Worker(new URL('./worker.mjs', import.meta.url), {
workerData: 10_000_000,
});
worker.on('message', (sum) => console.log('sum:', sum));// worker.mjs
import { parentPort, workerData } from 'node:worker_threads';
let sum = 0;
for (let i = 0; i < workerData; i++) sum += i;
parentPort.postMessage(sum);Run it with node main.mjs. Because the worker file ends in .mjs, it loads as an ES module. Node.js workers can use almost every built-in module, including fs, crypto, and http. A few process-wide operations are limited inside a worker. For example, process.chdir() is not available, and process.exit() stops only that worker.
Wrapping a worker in a promise
Most code wants a single result, so a promise wrapper is a common pattern. It handles all three outcomes: a message, an error, and an unexpected exit.
// run-worker.mjs
import { Worker } from 'node:worker_threads';
export function runWorker(file, data) {
return new Promise((resolve, reject) => {
const worker = new Worker(file, { workerData: data });
worker.once('message', resolve);
worker.once('error', reject);
worker.once('exit', (code) => {
if (code !== 0) reject(new Error(`Worker exited with code ${code}`));
});
});
}// app.mjs
import { runWorker } from './run-worker.mjs';
const sum = await runWorker(new URL('./worker.mjs', import.meta.url), 10_000_000);
console.log('sum:', sum);When the worker finishes its script and has nothing left to do, it exits with code 0. Calling reject after the promise has already resolved does nothing, so the exit handler is safe.
Comparing the two APIs
| Aspect | Web Workers (browser) | worker_threads (Node.js) |
|---|---|---|
| Create | `new Worker(url, { type })` | `new Worker(fileOrURL, { workerData })` |
| Initial input | first `postMessage` | `workerData` option |
| Worker's handle to parent | `self` | `parentPort` |
| Receive messages | `onmessage`, `event.data` | `on('message', value)` |
| Error reporting | `error` event | `'error'` and `'exit'` events |
| Stop | `terminate()` or `self.close()` | `terminate()` (returns a promise) |
| Shared memory | `SharedArrayBuffer`, only on cross-origin isolated pages | `SharedArrayBuffer`, always available |
| DOM access | none | not applicable |
Copying versus transferring
Structured cloning copies data. That is cheap for a number, but copying a 100 MB ArrayBuffer costs time and doubles the memory used. Both runtimes let you transfer the buffer instead. Ownership moves to the receiver, and the sender's buffer becomes detached, with a length of zero.
// browser main thread; Node.js accepts the same second argument
const data = new Float64Array(1_000_000);
worker.postMessage(data.buffer, [data.buffer]);
console.log(data.buffer.byteLength); // 0, the buffer now belongs to the workerShared memory
A SharedArrayBuffer is not copied or moved. Both threads see the same bytes. To coordinate access, use Atomics operations such as Atomics.add, Atomics.wait, and Atomics.notify. Plain reads and writes from two threads can race. Browsers allow SharedArrayBuffer only when the page is cross-origin isolated. That means the server must send Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp. You can check self.crossOriginIsolated at runtime. Node.js has no such requirement.
When workers help and when they hurt
Workers have a cost. Starting one means creating a new engine instance, which takes milliseconds and several megabytes of memory. Every message also adds cloning overhead. Use these points to decide:
- Use a worker for CPU-bound work that takes long enough to cause dropped frames (about 16 ms in a browser) or delayed requests. Image processing, parsing large files, compression, and cryptographic hashing are good fits.
- Do not use a worker for I/O in Node.js.
fs,net, andfetchare already asynchronous, and libuv's thread pool and the operating system handle the waiting. A worker only adds overhead. - Do not create a new worker for every small task. If tasks repeat, keep a pool of long-lived workers, usually about as many as
os.availableParallelism()in Node.js ornavigator.hardwareConcurrencyin the browser, and send them jobs as messages. - If the work is short but frequent, measure first. Cloning the input can cost more than the computation saves.
Common failure modes
- The worker never replies. The worker threw an error, and no
errorlistener was attached. Always listen for errors. DataCloneErrorin the browser, or aDataCloneErrorDOMExceptionin Node.js. You posted a function, a DOM node, or an object that contains one. Send plain data instead.- A browser worker fails to load on a
file://page. Serve the files over HTTP, for example withnpx serve. - A Node.js process does not exit. A worker that is still listening keeps the process alive. Call
worker.terminate()orworker.unref(). - Methods are missing after a message arrives. Class instances lose their prototype when cloned, so rebuild them on the receiving side.
Exercise
A Node.js script reads 500 files with fs.promises.readFile and the event loop feels slow. A teammate suggests moving the reads into worker_threads. Is this a good idea? Explain.
Show answer
Usually not. File reads through fs.promises are already asynchronous and run on libuv's thread pool, so they do not block the main thread. Workers would add startup and cloning costs without making the waiting any shorter. A worker would help only if the CPU work done on the file contents afterward, such as parsing, is what blocks the loop.
Exercise
In the browser, main.js runs const arr = new Uint8Array(1024); worker.postMessage(arr.buffer, [arr.buffer]); console.log(arr.length, arr.buffer.byteLength);. What is logged, and why?
Show answer
It logs "0 0". The buffer was transferred, not copied, so it is detached on the main thread. Detaching sets the buffer's byteLength to 0 and makes every view on it, including arr, report a length of 0.
Exercise
You post { total: 5, format() { return 'x'; } } to a worker and get a DataCloneError. What is wrong, and how do you fix it?
Show answer
Structured cloning cannot copy functions, and the object contains the method format. Send only data, such as { total: 5 }, and define the formatting logic inside the worker or on the receiving side.
Exercise
Write the minimum change to the Web Worker example so the main thread logs an error message if worker.js throws.
Show answer
Add an error listener before posting the message: worker.onerror = (event) => console.error('worker failed:', event.message);. Without it, the main thread gets no notification and its onmessage handler never runs.