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 resourcesBest 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