← Back to JavaScript, page 5

javascript-0081 · Medium mid

What are Web Workers, how do they communicate with the main thread, and what can they not do?

A Web Worker runs JavaScript on a separate thread with its own global scope, so heavy computation does not freeze the page. The main thread and the worker communicate only by messages, whose data is copied with the structured clone algorithm (or transferred). A worker cannot touch the DOM, and each worker costs memory, so use a few for real heavy work.

Full answer

Because JavaScript on a page runs on one main thread, a long computation blocks clicks, animations, and rendering. A Web Worker moves the work to another thread. It starts from a separate script file or a blob, with its own global object (self), its own event loop, and no shared variables with the page.

Communication is by message passing. The page calls worker.postMessage(data) and listens with worker.onmessage; the worker does the same in reverse with self.postMessage and self.onmessage. Data is copied with the structured clone algorithm, so objects are duplicated, not shared, and functions or DOM nodes cannot be sent. For large binary data, a transferable ArrayBuffer moves without copying. Shared memory is possible with SharedArrayBuffer and Atomics under special security requirements.

What a worker cannot do: it cannot read or change the DOM, and it has no window or document. It can use fetch, timers, IndexedDB, WebSocket, crypto, and importScripts or module imports. Errors in a worker surface through its error event on the main thread. worker.terminate() stops it at once from the outside, and self.close() from the inside.

When to use them: parsing a large file, image processing, encryption, search indexing, or any task over about 50 ms. They are not helpful for waiting on network requests, as those already do not block. Message passing has a cost, and each worker uses its own memory, so a small pool is usually better than dozens.

Dedicated workers serve one page. Shared workers serve several tabs, and service workers sit between the page and the network, which is a separate topic.

Node.js has worker_threads, which follows the same ideas with different names. The code below uses it, because it can be run here.

javascript
const { Worker } = require('node:worker_threads');

const workerSource = `
  const { parentPort } = require('node:worker_threads');
  parentPort.on('message', (job) => {
    if (job.type === 'sum') {
      let total = 0;
      for (let i = 1; i <= job.limit; i++) total += i % 7;
      parentPort.postMessage({ type: 'result', total, echo: job.label });
    } else if (job.type === 'fail') {
      throw new Error('worker crashed on purpose');
    }
  });
`;

const worker = new Worker(workerSource, { eval: true });
const events = [];

worker.on('message', (message) => {
  events.push(`worker replied: ${message.echo} = ${message.total}`);
  console.log(events.join('\n'));
  worker.postMessage({ type: 'fail' });
});
worker.on('error', (error) => {
  console.log('error event on the main thread:', error.message);
});
worker.on('exit', (code) => {
  console.log('worker exited with code', code);
});

const original = { label: 'sum of i mod 7 over 300 million values', limit: 300_000_000, type: 'sum' };
worker.postMessage(original);
original.label = 'changed after sending'; // the worker received a copy, so this has no effect

setTimeout(() => events.push('main thread still free: timer fired'), 20);
events.push('message sent, main thread continues');

Run with Node.js v24.22.1 as js-81.js; two runs gave identical output. Output: message sent, main thread continues main thread still free: timer fired worker replied: sum of i mod 7 over 300 million values = 900000003 error event on the main thread: worker crashed on purpose worker exited with code 1

Key points

  • A worker runs on another thread with its own global scope and event loop.
  • Communication is by postMessage; data is copied (structured clone) or transferred.
  • Workers cannot access the DOM or window.
  • Use workers for tasks over about 50 ms; they do not help with waiting on I/O.
  • Terminate unused workers; each one costs memory.

Common mistakes

  • Trying to use document or window inside a worker.
  • Sending a function or DOM node in a message and getting a DataCloneError.
  • Starting a new worker for every small task, so startup and memory cost outweigh the benefit.
  • Forgetting to terminate workers that are no longer needed.

Follow-ups

  • How would you build a small pool of workers and queue tasks?
  • What is the difference between a dedicated worker, a shared worker, and a service worker?
  • How can a worker and the main thread share memory safely?

Tips

  • Say that the benefit is keeping the main thread free, not making the computation itself faster.
  • Mention structured clone and transfer for message data.
  • Give the rough threshold of 50 ms for when a worker is worth it.