Web Worker

A JavaScript script that runs in a background thread separate from the main execution thread, allowing you to perform tasks without blocking the UI.

Overview

Web Workers allow you to run JavaScript in background threads, enabling true multi-threading in web applications. They're perfect for computationally intensive tasks that would otherwise freeze the user interface. Workers communicate with the main thread via message passing and don't have access to the DOM.

Example

javascript
// main.js - Create and use worker
const worker = new Worker('worker.js');

// Send message to worker
worker.postMessage({ numbers: [1, 2, 3, 4, 5] });

// Receive message from worker
worker.onmessage = function(event) {
  console.log('Result from worker:', event.data);
};

// Handle errors
worker.onerror = function(error) {
  console.error('Worker error:', error);
};

// Terminate worker when done
worker.terminate();

// worker.js - Worker script
self.onmessage = function(event) {
  const numbers = event.data.numbers;

  // Perform heavy computation
  const sum = numbers.reduce((acc, num) => acc + num, 0);

  // Send result back to main thread
  self.postMessage(sum);
};

// Practical example: Process large dataset
function processLargeDataset(data) {
  const worker = new Worker('process-worker.js');

  return new Promise((resolve, reject) => {
    worker.onmessage = (e) => {
      resolve(e.data);
      worker.terminate();
    };

    worker.onerror = (e) => {
      reject(e);
      worker.terminate();
    };

    worker.postMessage(data);
  });
}

Key Points

  • Runs JavaScript in background thread
  • No access to DOM or window object
  • Communicates via postMessage
  • Good for heavy computations
  • Different from Service Workers

Learn More