Sub topic 13
Moving Work Off the Main Thread
This chapter assumes you already know how the event loop schedules tasks and microtasks, and that you can write ES modules for Node.js. It shows how to run CPU-heavy code on a separate thread in each runtime, so the main thread stays free.
Why the main thread gets stuck
JavaScript runs your code on one thread, called the main thread. The event loop can only pick the next task after the current one finishes. Async I/O avoids blocking because the runtime does the waiting outside your code. A long loop is different: it keeps the thread busy until it ends.
In a browser, a busy main thread means clicks, scrolling, and rendering all pause. In Node.js, it means the server stops answering requests until the loop finishes. Wrapping the loop in a promise or async function does not help, because the work still runs on the same thread.
A worker is a separate thread with its own engine instance, its own global scope, and its own event loop. The main thread and the worker share no variables. They exchange messages, and each message is copied using the structured clone algorithm.
Web Workers in the browser
The browser API is Worker. You pass it the URL of a script, and that script runs in a worker scope where self is the global object. Workers have no document and cannot touch the DOM.
// main.js (browser)
const worker = new Worker('worker.js');
worker.onmessage = (event) => console.log('sum:', event.data);
worker.postMessage(10_000_000);// worker.js
self.onmessage = (event) => {
let sum = 0;
for (let i = 0; i < event.data; i++) sum += i;
self.postMessage(sum);
};Serve both files from a local web server. Most browsers refuse to start workers from file:// URLs. To write the worker as an ES module, use new Worker('worker.js', { type: 'module' }).
worker_threads in Node.js
Node.js provides the same idea through the node:worker_threads module. You can pass the starting input as workerData, and the worker replies 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. Building the path with new URL(..., import.meta.url) resolves the worker file relative to the module, not to the directory you launched Node.js from.
Comparing the two APIs
| Aspect | Web Workers | worker_threads |
|---|---|---|
| Create | `new Worker(url)` | `new Worker(pathOrURL, options)` |
| Initial input | first `postMessage` | `workerData` option |
| Send from worker | `self.postMessage` | `parentPort.postMessage` |
| Receive in main | `onmessage` / `event.data` | `on('message', value)` |
| Access to host APIs | no DOM | full Node.js modules |
Common errors
- Sending functions or DOM nodes. Structured clone cannot copy them, so
postMessagethrows aDataCloneError. Send plain data instead. - Expecting shared state. Changing an object after you post it does not change the worker's copy. If you really need shared memory, use
SharedArrayBufferwithAtomics. - Using workers for I/O. File and network calls are already asynchronous. Workers help with CPU-bound work like parsing, compression, or image processing.
- Spawning a worker per job. Each worker costs startup time and memory. For repeated work, keep a small pool alive and reuse it.
Exercise
A page runs await new Promise((r) => r(heavyLoop())) and the UI still freezes. Why, and how do you fix it?
Show answer
The promise executor runs synchronously on the main thread, so heavyLoop blocks the event loop no matter how it is wrapped. Move heavyLoop into a Web Worker, post the input to the worker, and resolve the promise when the worker's message event arrives.
Exercise
In the Node.js example, what is logged if worker.mjs calls parentPort.postMessage(() => sum)?
Show answer
Nothing is logged. Functions cannot be structured-cloned, so postMessage throws a DataCloneError inside the worker, and the main thread receives an 'error' event rather than a 'message' event.