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

JS Web Workers

A Web Worker runs a heavy job in the background so the page does not freeze, like a helper working in another room. You send it messages and it sends answers back.
Syntax
javascript
const worker = new Worker("worker.js");
worker.postMessage(data);
worker.onmessage = function(event) {
  // event.data
};

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.

उदाहरण: What Is a Web Worker?

javascript
// Declare the constant `workerCode`, set to `postMessage("Worker started");`
// Declare the constant `workerCode`, set to `postMessage("Worker started");`
const workerCode = `postMessage("Worker started");`;
// Declare the constant `blob` as a new `Blob` instance
// Declare the constant `blob` as a new `Blob` instance
const blob = new Blob([workerCode], { type: "application/javascript" });
// Declare the constant `worker` as a new `Worker` instance
// Declare the constant `worker` as a new `Worker` instance
const worker = new Worker(URL.createObjectURL(blob));
// Assign `(e) => console.log(e.data)` to `worker.onmessage`
// Assign `(e) => console.log(e.data)` to `worker.onmessage`
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.

उदाहरण: postMessage()

javascript
// Declare the constant `workerCode`, set to `onmessage = (e) => postMessage("Received: " + e.data);`
// Declare the constant `workerCode`, set to `onmessage = (e) => postMessage("Received: " + e.data);`
const workerCode = `onmessage = (e) => postMessage("Received: " + e.data);`;
// Declare the constant `worker` as a new `Worker` instance
// Declare the constant `worker` as a new `Worker` instance
const worker = new Worker(URL.createObjectURL(new Blob([workerCode])));
// Assign `(e) => console.log(e.data)` to `worker.onmessage`
// Assign `(e) => console.log(e.data)` to `worker.onmessage`
worker.onmessage = (e) => console.log(e.data);
// Call `worker.postMessage("Hello")`
// Call `worker.postMessage("Hello")`
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.

उदाहरण: Worker Errors

javascript
// Declare the constant `workerCode`, set to `throw new Error("Worker failed");`
// Declare the constant `workerCode`, set to `throw new Error("Worker failed");`
const workerCode = `throw new Error("Worker failed");`;
// Declare the constant `worker` as a new `Worker` instance
// Declare the constant `worker` as a new `Worker` instance
const worker = new Worker(URL.createObjectURL(new Blob([workerCode])));
// Assign `(e) => console.log("Worker error:", e.message)` to `worker.onerror`
// Assign `(e) => console.log("Worker error:", e.message)` to `worker.onerror`
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.

उदाहरण: 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.

उदाहरण: Practical Use

javascript
// Declare the constant `workerCode`, set to `
const workerCode = `
  let total = 0;
  for (let i = 0; i < 1e6; i++) total += i;
  postMessage(total);
`;
// Declare the constant `worker` as a new `Worker` instance
const worker = new Worker(URL.createObjectURL(new Blob([workerCode])));
// Assign `(e) => console.log("Heavy computation result:", e.data)` to `worker.onmessage`
worker.onmessage = (e) => console.log("Heavy computation result:", e.data);
Live Example
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}

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.