Web Workers
Running JavaScript in background threads — keeping the UI responsive during heavy computation.
What it is, in plain English: A Web Worker runs JavaScript in a background thread, separate from the main thread that handles the UI. This means heavy computation can run without freezing the page. Workers communicate with the main thread via postMessage() and onmessage — they can't access the DOM directly. SharedArrayBuffer enables shared memory between workers, with Atomics for thread-safe operations.
Moving heavy work off the main thread
JavaScript runs on a single main thread — the same thread that handles user clicks, animations, and DOM updates. If your code does something heavy (processing a large dataset, running image filters, parsing a huge file), it blocks everything else. The page freezes. Buttons don't respond.
Web Workers solve this by running code in a separate background thread.
Creating a worker
// worker.js — runs in background thread
// No access to: window, document, DOM
// Full access to: fetch, setTimeout, IndexedDB, crypto, WebSockets, Canvas (OffscreenCanvas)
self.onmessage = function(event) {
const numbers = event.data; // received from main thread
// Heavy computation — doesn't block the UI:
const sorted = [...numbers].sort((a, b) => a - b);
const sum = sorted.reduce((s, n) => s + n, 0);
const mean = sum / sorted.length;
// Send result back:
self.postMessage({ sorted, mean });
};// main.js — the page's JavaScript
const worker = new Worker("worker.js");
// Send data to the worker:
const bigArray = Array.from({ length: 1000000 }, () => Math.random());
worker.postMessage(bigArray);
// Receive result from worker:
worker.onmessage = (event) => {
const { sorted, mean } = event.data;
console.log("Mean:", mean.toFixed(4));
displayResults(sorted);
};
worker.onerror = (error) => {
console.error("Worker failed:", error.message);
};
// The page stays responsive while the worker computes!
// Buttons still work, animations still playTerminating a worker
// From the main thread — kill the worker immediately:
worker.terminate();
// From inside the worker itself:
// self.close();
Try It Yourself
Official Sources
- MDN Web Docs — Web Workers API
- MDN Web Docs — Using Web Workers
- MDN Web Docs — SharedArrayBuffer
- Comlink — GitHub
The Codex links only to official documentation and the ECMAScript specification. No third-party tutorials.