iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Web Worker API

A Web Worker runs JavaScript in a background thread. The main thread keeps painting and responding to input; the worker does the heavy lifting.

Creating one

app.js (main thread)
const worker = new Worker("worker.js", { type: "module" });

worker.postMessage({ type: "factor", number: 982451653 });

worker.addEventListener("message", (e) => {
  console.log("result:", e.data);
});

worker.terminate();   // stop it for good
worker.js
self.addEventListener("message", (e) => {
  if (e.data.type === "factor") {
    self.postMessage(factor(e.data.number));
  }
});

function factor(n) { /* … */ }

What's available inside a worker

YesNo
fetch, setTimeout, setIntervalThe DOM (document, window)
IndexedDB, cacheslocalStorage
WebSocket, WebRTCDirect DOM access
ES modules with importSynchronous network calls
OffscreenCanvas

Three worker flavours

TypeUse
Dedicated WorkerOne worker, one page — the example above.
Shared WorkerOne worker shared across tabs of the same origin.
Service WorkerProxy for network requests; powers PWAs and offline.

Transferable objects — zero-copy hand-off

JS
// Buffer ownership moves to the worker — main thread cannot use it anymore
const buf = new ArrayBuffer(1024 * 1024);
worker.postMessage({ buf }, [buf]);
Tip: Reach for a worker when you spot main-thread frame drops during heavy work — image processing, parsing big JSON, search indexes. Below ~5 ms of CPU per call, the message overhead isn't worth it.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from Web Worker API!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Send a job to a worker.

worker. ({ type: 'render', data });

Test yourself

Q1. Web Workers do NOT have access to…
Q2. Send a message to a worker with…
Q3. Stop a worker permanently with…

Discussion

Loading…