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

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation

Async/Await
Async/await is modern JavaScript syntax for handling asynchronous operations, making asynchronous code look and behave like synchronous code. The async keyword marks a function as asynchronous, and await pauses execution until a Promise resolves. This approach makes asynchronous code more readable and easier to understand than traditional Promise chains or callbacks.
Promises
A Promise represents a value that may not be available yet - the eventual result of an asynchronous operation. It exists in one of three states: pending, fulfilled, or rejected. then() handles a successful result, catch() handles an error, and finally() runs regardless of outcome. Promises are the foundation that async/await is built on top of.
Promise.all(), allSettled(), race(), any()
These static methods handle multiple promises at once. Promise.all() waits for every promise to resolve, but rejects immediately if any one fails. allSettled() waits for all to finish regardless of outcome, giving you both successes and failures. race() resolves or rejects as soon as the first promise settles. any() resolves as soon as the first one succeeds, ignoring rejections unless all fail.
Fetch API
The Fetch API provides a modern, promise-based way to make HTTP requests, replacing the older XMLHttpRequest. fetch() returns a promise that resolves to a Response object once headers are received - note that a Response is only considered "ok" if the status is 2xx, so checking response.ok is essential, since fetch() does not reject on HTTP error statuses.