Skip to content
Tutorials Center
My learning

Topics

Lesson 102 of 156 ยท Browser APIs

Web Workers and Parallel JavaScript

Run heavy JavaScript off the main thread with Web Workers - postMessage, structured clone, transferable buffers, error handling, a promise wrapper and when workers help.

JavaScript in a web page runs on a single thread, the main thread, and that same thread also handles clicks, scrolling, layout and painting. While a long calculation is running, none of those can happen: the page freezes, buttons do not react and animations stutter. You cannot fix that with async and await, because those only reorder waiting. A loop that burns CPU for two seconds blocks the page for two seconds no matter how it is wrapped.

Web Workers fix the real problem. A worker is a second JavaScript thread that the browser runs in the background. You hand it work, it computes on its own thread, and it sends the answer back as a message. The page stays smooth the whole time. In this lesson you will create workers, exchange messages, move big buffers without copying them, handle failures, wrap a worker in a promise-based function and decide when a worker is actually worth it.

Workers share nothing

A worker lives in a completely separate global scope. It has its own variables, its own event loop and no access to the DOM: there is no document, no window and no way to touch an element. It does have self (its global object), fetch, timers, crypto, console, URL, indexedDB, WebSocket and most other APIs that do not need a page.

Because nothing is shared, the two sides cannot corrupt each other's data. They communicate only by sending messages:

sequenceDiagram
  participant P as Page (main thread)
  participant W as Worker thread
  P->>W: worker.postMessage(data)
  Note over W: onmessage runs,<br/>heavy work happens here
  W->>P: self.postMessage(result)
  Note over P: worker.onmessage runs,<br/>update the page

Messages travel in both directions. Each side listens with onmessage.

Your first worker

A worker normally lives in its own file. The page creates it with new Worker(url):

JavaScript
// Read-only: main.js
const worker = new Worker("/js/prime-worker.js");

worker.addEventListener("message", (event) => {
  console.log("Result from worker:", event.data);
});

worker.postMessage({ limit: 2_000_000 });
JavaScript
// Read-only: /js/prime-worker.js
self.addEventListener("message", (event) => {
  const { limit } = event.data;
  let count = 0;
  for (let n = 2; n <= limit; n++) {
    let isPrime = true;
    for (let d = 2; d * d <= n; d++) {
      if (n % d === 0) { isPrime = false; break; }
    }
    if (isPrime) count++;
  }
  self.postMessage({ limit, count });
});

The worker file is a normal script. When the page posts a message, the worker's message event fires; the worker answers with self.postMessage(). The file must be served from your own origin.

Running workers in this lesson. The editors on this site run inside a sandbox that has no URL for a separate worker file. A worker can also be created from a string of code through a Blob URL, and that works here, so the runnable examples below use that technique. In your own projects you will normally use a separate file, as above.

A worker without a separate file

URL.createObjectURL(blob) turns a string into a temporary URL that new Worker() accepts. Run this one and watch the two threads talk:

JS A worker from a Blob URL

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The "Message sent" line prints first: postMessage returns immediately and the answer arrives later as an event. worker.terminate() stops a worker from the outside; a worker can also stop itself with self.close(). An idle worker keeps a thread alive, so always clean up the ones you no longer need.

What can you send?

Messages are copied with the structured clone algorithm, the same one behind structuredClone(). It handles far more than JSON does:

  • primitives, plain objects, arrays, nested structures and circular references
  • Date, RegExp, Map, Set, BigInt
  • ArrayBuffer, typed arrays, Blob, File, ImageData, ImageBitmap
  • Error objects (name and message survive)

It cannot copy functions or DOM nodes, and a class instance arrives as a plain object without its prototype (so its methods are gone). Sending a function throws a DataCloneError.

JS What survives the trip

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The Date and Map arrive intact, while the Point loses its prototype, so its method is gone. Send plain data, and rebuild class instances on the receiving side if you need them.

Transferables: moving instead of copying

Copying a 100 MB buffer for every message would be slow and would double the memory use. For ArrayBuffer, MessagePort, ImageBitmap and a few other types you can pass a second argument to postMessage: a list of objects to transfer. Ownership moves to the other thread with no copy, and the sender's version becomes empty (detached).

JS Transfer an ArrayBuffer

Press Run (or Ctrl + Enter) to see the console output here.

No output.

After the call, buffer.byteLength is 0: the page no longer owns the memory. Transfer when you send large binary data one way; copy (the default) when both sides need to keep it.

Handling errors

An uncaught exception inside a worker does not crash the page. It fires an error event on the Worker object, with the message and the line number. A message that cannot be deserialized triggers messageerror.

JS Catching a worker's error

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first message works normally and the second one reports the error. After an error the worker is still alive and keeps handling messages, unless you terminate it as the example does. Inside a worker, a rejected promise that nobody handles produces an unhandledrejection event instead.

Turning messages into promises

Messages are event-based, but most application code prefers await. A small wrapper gives every request an id, remembers the matching resolve and reject, and settles the promise when a reply with that id comes back:

JS A promise-based worker call

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Now the worker looks like an ordinary async function to the rest of your code, and several calls can be in flight at the same time because each reply finds its own promise by id. Libraries such as Comlink build this idea out fully, but the core is this small.

Module workers and importing code

A classic worker pulls in other scripts with importScripts("a.js", "b.js"), which loads them synchronously. Modern code uses a module worker, which supports import and export like any other module:

JavaScript
// Read-only: main.js
const worker = new Worker(new URL("./report-worker.js", import.meta.url), {
  type: "module",
});
JavaScript
// Read-only: report-worker.js
import { summarize } from "./stats.js";

self.onmessage = ({ data }) => {
  self.postMessage(summarize(data));
};

Bundlers such as Vite and webpack recognise the new Worker(new URL(..., import.meta.url)) pattern and package the worker file for you.

Other kinds of workers

  • Dedicated workers (this lesson) belong to the one page that created them.
  • Shared workers (new SharedWorker(url)) can be reached from several tabs of the same origin through ports. Handy for one shared connection, but support is weaker, so check before relying on it.
  • Service workers sit between your page and the network, as covered in Service Workers and the Cache API.
  • Worklets run tiny pieces of code inside the browser's audio or rendering pipeline.

A browser also limits how many workers it will run well. A reasonable pool size is navigator.hardwareConcurrency (the number of logical cores), often minus one so the main thread keeps a core.

When a worker helps, and when it does not

Workers are not free. Starting one costs a few milliseconds and some memory, and every message is a copy (or a transfer). Use one when:

  • a task takes longer than roughly 50 ms and would visibly block the page (image filters, parsing a big file, sorting a huge array, compression, encryption, searching a large in-memory index);
  • the work is self-contained: data in, result out;
  • you want to run several independent jobs in parallel on multiple cores.

Do not use one for:

  • waiting on the network. fetch is already non-blocking, so a worker adds nothing;
  • touching the DOM. A worker cannot, so a worker plus a DOM update still needs a message round trip;
  • tiny jobs where the message cost outweighs the work.

Before reaching for a worker, check the simpler fixes: a better algorithm, splitting a loop into chunks with timers so the page can breathe, or doing less work in the first place.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does wrapping a slow CPU-bound loop in an async function not stop it from freezing the page?

    async/await only reorders waiting. The loop still runs on the single main thread, so nothing else can happen until it ends. A worker moves it to another thread.
  2. 2. Which of these can code inside a dedicated worker use?

    Workers have no DOM and share no variables with the page, but they can use fetch, timers, crypto, WebSocket and other APIs that do not need a document.
  3. 3. After worker.postMessage(buffer, [buffer]), what is buffer.byteLength on the sending side?

    Listing an ArrayBuffer as transferable moves it without copying. The sender's buffer is detached and reports a length of 0.
  4. 4. What happens when you post an object that contains a function?

    Structured cloning cannot copy functions or DOM nodes, so postMessage throws a DataCloneError.
  5. 5. Which task is a poor fit for a worker?

    fetch is already asynchronous and does not block the main thread, so moving it into a worker gains nothing. CPU-heavy, self-contained jobs are what workers are for.

Summary

  • A Web Worker runs JavaScript on a separate thread, so heavy work does not freeze the page.
  • Workers have no DOM and share no variables; they communicate with postMessage and message events.
  • Messages are copied with the structured clone algorithm (rich types, but no functions or DOM nodes). Transfer big ArrayBuffers to move them without copying.
  • Handle failures with the worker's error event, and stop workers with terminate() or self.close().
  • Wrap messages in ids and promises to use workers with await.
  • Use type: "module" for import support; use workers for long, self-contained, CPU-bound jobs, not for network waits.

Next, learn the browser's built-in way to move things around the page with the mouse: The Drag and Drop API.