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 (
Selfinstead ofWindow).
β οΈ Important Limitations
| Feature | Main Thread | Web Worker |
|---|---|---|
| DOM Access | Yes | No (Cannot access document or window) |
| LocalStorage | Yes | No |
| IndexedDB | Yes | Yes |
| Fetch API | Yes | Yes |
| WebSockets | Yes | Yes |
π Advanced Types
- Shared Workers: Can be accessed by multiple scripts from different windows or iframes on the same origin.
- 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.onerrorto catch exceptions in the background thread. - Termination: Call
worker.terminate()when the worker is no longer needed to free up system resources.