Codectionary / Developer documentation / JavaScript

Web Workers

Web Workers run JavaScript on a separate background thread, away from the main UI thread, so expensive computations do not freeze the page. Communication between the main script and a worker happens through message passing with postMessage() and the onmessage event handler, rather than shared memory - workers cannot directly access the DOM.

Syntax

const worker = new Worker("worker.js");
worker.postMessage(data);

Examples

Creating and Communicating with a Worker

Offloading a heavy computation to a background thread.

// main.js
const worker = new Worker("worker.js");

worker.postMessage({ command: "calculate", number: 40 });

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

worker.onerror = (error) => {
  console.log("Worker error:", error.message);
};

The Worker Script Itself

The code running inside the separate worker thread.

// worker.js
self.onmessage = (event) => {
  const { command, number } = event.data;

  if (command === "calculate") {
    const result = fibonacci(number); // expensive, would freeze the UI if run on the main thread
    self.postMessage(result);
  }
};

function fibonacci(n) {
  return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);
}

Terminating a Worker

Cleaning up a worker once it is no longer needed.

const worker = new Worker("worker.js");

// ... use the worker ...

worker.terminate(); // immediately stops the worker and frees its resources

Best practices

  • Use Web Workers for genuinely expensive, CPU-bound tasks (heavy computation, large data processing) that would otherwise freeze the UI
  • Remember workers cannot access the DOM, window, or parent objects directly - all communication happens via postMessage()
  • Terminate workers with terminate() once they are no longer needed, to free up system resources
  • Keep messages passed to/from workers simple and serializable - complex objects with functions or circular references cannot be passed directly

Runtime & versions

Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

ECMAScript specification

Specifications & further reading