Skip to content

Web Workers: Multi-threading in JavaScript

Web Workers: Multi-threading in JavaScript

JavaScript is single-threaded by nature, meaning it can only do one thing at a time on the β€œMain Thread.” Web Workers allow you to run script in background threads, enabling truly parallel execution without blocking the user interface.


πŸ—οΈ How it Works

A Web Worker is a separate file that runs in its own thread. It communicates with the main thread using an asynchronous messaging system (postMessage).

1. The Main Thread (Main.js)

// Create a new worker
const worker = new Worker('worker.js');

// Send data to the worker
worker.postMessage({ id: 1, action: 'compute' });

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

2. The Worker Thread (worker.js)

// Listen for messages from the main thread
onmessage = (event) => {
    const data = event.data;
    
    // Perform heavy computation
    const result = performHeavyTask(data);
    
    // Send result back
    postMessage(result);
};

πŸš€ Why Use Web Workers?

  • Zero UI Lag: Keep animations and user interactions at 60 FPS while processing data.
  • Parallelism: Offload encryption, image processing, or large data parsing.
  • Independent Context: Workers run in a different global context (Self instead of Window).

⚠️ Important Limitations

FeatureMain ThreadWeb Worker
DOM AccessYesNo (Cannot access document or window)
LocalStorageYesNo
IndexedDBYesYes
Fetch APIYesYes
WebSocketsYesYes

πŸ“ˆ Advanced Types

  1. Shared Workers: Can be accessed by multiple scripts from different windows or iframes on the same origin.
  2. Service Workers: Act as a proxy between the app and the network. Key for offline support (PWA) and push notifications.

πŸ’‘ Best Practices

  • Minimize Transfer Cost: Passing large objects between threads can be slow (structured cloning). Use Transferable Objects (like ArrayBuffer) for zero-copy data transfer.
  • Error Handling: Always implement worker.onerror to catch exceptions in the background thread.
  • Termination: Call worker.terminate() when the worker is no longer needed to free up system resources.