← Back to JavaScript Course | Chapter 9: Async & Web APIs | Lesson 8 of 26

JS Web Workers

What Is a Web Worker?

A Web Worker runs JavaScript in a separate browser thread and can handle heavy work away from the main UI thread. Because a worker runs on its own thread, expensive computations there don't freeze scrolling, animations, or user input on the main page.

Example: What Is a Web Worker?

javascript
const workerCode = `postMessage("Worker started");`;
const blob = new Blob([workerCode], { type: "application/javascript" });
const worker = new Worker(URL.createObjectURL(blob));
worker.onmessage = (e) => console.log(e.data);

postMessage()

The main thread and worker exchange data with postMessage(). Workers don't share memory with the main thread, so all communication happens by sending copies of data back and forth through postMessage(), not by direct variable access.

Example: postMessage()

javascript
const workerCode = `onmessage = (e) => postMessage("Received: " + e.data);`;
const worker = new Worker(URL.createObjectURL(new Blob([workerCode])));
worker.onmessage = (e) => console.log(e.data);
worker.postMessage("Hello");

Worker Errors

Workers can report errors to the main thread with the error event. Listening for the worker's error event lets the main thread catch and handle failures happening inside the worker's separate execution context.

Example: Worker Errors

javascript
const workerCode = `throw new Error("Worker failed");`;
const worker = new Worker(URL.createObjectURL(new Blob([workerCode])));
worker.onerror = (e) => console.log("Worker error:", e.message);

Terminate a Worker

terminate() stops a worker when it is no longer needed. Calling terminate() immediately stops the worker's script entirely, which is important for freeing up resources once its work is genuinely finished.

Example: Terminate a Worker

javascript
const workerCode = `postMessage("Running");`;
const worker = new Worker(URL.createObjectURL(new Blob([workerCode])));
worker.onmessage = (e) => {
  console.log(e.data);
  worker.terminate(); // stop the worker once done
};

Practical Use

Web Workers are useful for CPU-heavy calculations and data processing that should not block the page. A typical use case is running a large data-processing or image-manipulation task in a worker so the page stays responsive while it happens.

Example: Practical Use

javascript
const workerCode = `
  let total = 0;
  for (let i = 0; i < 1e6; i++) total += i;
  postMessage(total);
`;
const worker = new Worker(URL.createObjectURL(new Blob([workerCode])));
worker.onmessage = (e) => console.log("Heavy computation result:", e.data);

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.