Web Workers

Updated · 8 min read
mediumES2026javascriptweb-workersthreadspostmessageperformance

A Web Worker runs JavaScript on a separate thread, in the background, so heavy work doesn't freeze the page. The main thread, where your page's code, rendering and event handling happen, can only do one thing at a time; a long calculation there makes clicks and scrolling stop responding. A worker runs in parallel with its own global scope and talks to the page only by sending messages. This course's own Try it button works this way: your code runs in a worker, so an endless loop can't freeze the lesson page.

In One Minute

  • Create a worker with new Worker("worker.js", { type: "module" }).
  • Send data with worker.postMessage(data); receive it with worker.addEventListener("message", e => e.data). Inside the worker, self.postMessage and self.onmessage do the same.
  • Data is copied (structured clone), not shared; large buffers can be transferred instead.
  • Workers have no DOM access: no document, no window. They do have fetch, timers, IndexedDB and most other APIs.
  • Stop a worker with worker.terminate() (from the page) or self.close() (inside).

Why Workers

blocking.html
<script>
  const start = performance.now();
  let ticks = 0;
  const timer = setInterval(() => ticks++, 10);

  while (performance.now() - start < 100) {
    // a heavy calculation that keeps the main thread busy for 100 ms
  }

  setTimeout(() => {
    clearInterval(timer);
    console.log(`busy for over 50 ms: ${performance.now() - start > 50}`);
    console.log(`timer ticks during the loop: ${ticks}`);
  }, 0);
</script>
Output
busy for over 50 ms: true
timer ticks during the loop: 0

Explanation: the timer should tick every 10 ms, but while the loop ran on the main thread, nothing else could run, not even the timer. In a real page, clicks, typing and scrolling would freeze the same way. Moving that loop into a worker keeps the page responsive.

Creating a Worker

A worker runs a separate script file. The page creates it and exchanges messages with it:

main.js
const worker = new Worker(new URL("./totals-worker.js", import.meta.url), { type: "module" });
 
worker.addEventListener("message", (event) => {
  console.log("Total from worker:", event.data.total);
});
worker.addEventListener("error", (event) => {
  console.error("Worker failed:", event.message);
});
 
worker.postMessage({ payments: [120, 85, 45] });
totals-worker.js
self.addEventListener("message", (event) => {
  const total = event.data.payments.reduce((sum, p) => sum + p, 0);
  self.postMessage({ total });
});

{ type: "module" } lets the worker use import and export; new URL("./file.js", import.meta.url) resolves the path relative to the current module, which bundlers also understand.

The checker runs single HTML pages, so the next example builds the worker's code from a string with a Blob URL, which works the same way:

worker.html
<p id="status">Working...</p>
<script>
  const workerCode = `
    self.addEventListener("message", (event) => {
      let total = 0;
      for (const amount of event.data.payments) total += amount;
      self.postMessage({ total, count: event.data.payments.length });
    });
  `;
  const url = URL.createObjectURL(new Blob([workerCode], { type: "text/javascript" }));
  const worker = new Worker(url);

  worker.addEventListener("message", (event) => {
    const { total, count } = event.data;
    document.querySelector("#status").textContent = `${count} payments, $${total}`;
    console.log(document.querySelector("#status").textContent);
    worker.terminate();
    URL.revokeObjectURL(url);
  });

  worker.postMessage({ payments: [120, 85, 45, 200] });
  console.log("Message sent; the page stays responsive");
</script>
Output
Message sent; the page stays responsive
4 payments, $450

Explanation: postMessage returned immediately, so the page's code continued. The worker computed the total on its own thread and posted the result back, which arrived as a message event. terminate() stops the worker when it's no longer needed.

Messages Are Copied

Data sent with postMessage is copied using the structured clone algorithm, the same one structuredClone uses. The worker gets its own copy; changing it doesn't affect the page's object:

Can be sentCan't be sent
Primitives, plain objects, arraysFunctions (DataCloneError)
Date, Map, Set, RegExpDOM elements
ArrayBuffer, typed arrays, Blob, FileClass instances keep data but lose their methods
Error objectsSymbols as values
Objects with circular references
clone.html
<script>
  const code = `self.onmessage = (e) => {
    e.data.items.push("changed in worker");
    self.postMessage({ when: e.data.when instanceof Date, size: e.data.tags.size, items: e.data.items.length });
  };`;
  const worker = new Worker(URL.createObjectURL(new Blob([code])));
  const original = { items: ["tuition"], when: new Date("2026-01-05T00:00:00"), tags: new Set(["paid"]) };

  worker.onmessage = (e) => {
    console.log(JSON.stringify(e.data));
    console.log("page still has", original.items.length, "item");
  };
  worker.postMessage(original);

  try {
    worker.postMessage({ format: () => "x" });
  } catch (err) {
    console.log(err.name);
  }
</script>
Output
DataCloneError
{"when":true,"size":1,"items":2}
page still has 1 item

The Date and Set arrived intact, the worker's change to its copy didn't affect original, and sending a function threw a DataCloneError immediately.

Transferring Large Data

Copying a large ArrayBuffer (an image, audio, a big dataset) takes time and doubles memory. Transferring moves ownership to the worker instantly; the page's buffer becomes empty:

transfer.html
<script>
  const worker = new Worker(URL.createObjectURL(new Blob([
    "self.onmessage = (e) => self.postMessage(e.data.byteLength);",
  ])));
  const buffer = new ArrayBuffer(8_000_000);

  worker.onmessage = (e) => console.log("worker received", e.data, "bytes");
  worker.postMessage(buffer, [buffer]);
  console.log("page buffer now", buffer.byteLength, "bytes");
</script>
Output
page buffer now 0 bytes
worker received 8000000 bytes

The second argument to postMessage lists the objects to transfer. After the transfer, the page can no longer use the buffer, which is what makes it safe to skip copying.

What Workers Can and Can't Do

Available in workersNot available
fetch, WebSocketdocument, window, any DOM element
setTimeout, setIntervalalert, confirm, prompt
IndexedDB, the Cache APIlocalStorage, sessionStorage
crypto, TextEncoder, URLDirect access to the page's variables
importScripts() (classic) or import (module workers)
OffscreenCanvas for drawing

The worker's global object is self (also globalThis), a DedicatedWorkerGlobalScope. To update the page, the worker sends a message and the page's code changes the DOM.

Errors and Cleanup

An uncaught error inside a worker fires an error event on the Worker object in the page; the worker keeps running unless the error was fatal. Workers also keep running until terminated, using memory:

errors.html
<script>
  const worker = new Worker(URL.createObjectURL(new Blob([
    "self.onmessage = (e) => { if (e.data < 0) throw new RangeError('negative amount'); self.postMessage(e.data * 2); };",
  ])));
  worker.onmessage = (e) => console.log("result:", e.data);
  worker.onerror = (e) => {
    e.preventDefault();
    console.log("worker error:", e.message);
  };
  worker.postMessage(-5);
  worker.postMessage(60);
  setTimeout(() => worker.terminate(), 200);
</script>
Output
worker error: Uncaught RangeError: negative amount
result: 120

The worker survived the first error and handled the second message. e.preventDefault() stops the error from also being reported in the page's console.

Other Kinds of Workers

WorkerPurpose
Dedicated worker (new Worker)Background computation for one page (this lesson)
Shared worker (new SharedWorker)One worker shared by several tabs of the same site
Service workerA proxy between the page and the network: offline support, caching, push notifications
Worklets (audio, paint)Small, specialized scripts that hook into the rendering or audio pipeline

In Practice

The Fee Tracker generates a year-end report over 200,000 payment records. Done on the main thread, the page would freeze; in a worker, a progress message updates the page while the work runs:

report.html
<p id="progress">Starting...</p>
<script>
  const code = `
    self.onmessage = (e) => {
      const count = e.data;
      let total = 0;
      for (let i = 1; i <= count; i++) {
        total += (i % 450) + 1;
        if (i % 50000 === 0) self.postMessage({ type: "progress", done: i });
      }
      self.postMessage({ type: "done", total });
    };`;
  const worker = new Worker(URL.createObjectURL(new Blob([code])));
  const progress = document.querySelector("#progress");

  worker.onmessage = ({ data }) => {
    progress.textContent = data.type === "progress" ? `Processed ${data.done.toLocaleString("en-US")}` : `Total: $${data.total.toLocaleString("en-US")}`;
    console.log(progress.textContent);
    if (data.type === "done") worker.terminate();
  };
  worker.postMessage(200_000);
</script>
Output
Processed 50,000
Processed 100,000
Processed 150,000
Processed 200,000
Total: $45,075,200

Common Mistakes

Touching the DOM in a worker. document is not defined. Send a message and update the DOM in the page.

Sending functions or DOM elements. DataCloneError. Send plain data.

Copying huge buffers. Transfer them: postMessage(buffer, [buffer]).

Never terminating workers. They keep running and using memory. Call terminate() when done.

Using a worker for tiny tasks. Starting a worker and copying messages has overhead; use workers for work that takes tens of milliseconds or more.

Practice

Challenge: Create a worker (from a Blob) that receives an array of numbers and replies with the largest one; log the reply and terminate the worker.

Show solution
max-worker.html
<script>
  const worker = new Worker(URL.createObjectURL(new Blob([
    "self.onmessage = (e) => self.postMessage(Math.max(...e.data));",
  ])));
  worker.onmessage = (e) => {
    console.log("largest:", e.data);
    worker.terminate();
  };
  worker.postMessage([120, 85, 450, 45]);
</script>
Output
largest: 450

Quick check: Web Workers

3 questions
1Why move heavy work into a Web Worker?
2What happens to an object sent with postMessage?
3Which is NOT available inside a worker?

Key Takeaways

TaskCode
Createnew Worker(url, { type: "module" })
Sendworker.postMessage(data)
Receiveworker.addEventListener("message", (e) => e.data)
Reply (in worker)self.postMessage(result)
Transfer a bufferworker.postMessage(buf, [buf])
Stopworker.terminate()

Was this tutorial helpful?

Lesson 83 of 139