Web Workers & Multithreading in JS
Web Workers & Multithreading in Modern JavaScript
While JavaScript is famous for its single-threaded Event Loop, modern browsers provide true hardware-level multithreading via the Web Workers API. Web Workers run scripts in background threads, enabling CPU-intensive operations (image processing, cryptographic hashing, 3D physics, big-data filtering) without blocking the main UI thread.
1. Main Thread vs. Worker Thread
What Workers CANNOT Access:
- The DOM (
document.querySelector,window) parentobject- Local DOM nodes
What Workers CAN Access:
fetch()andXMLHttpRequestIndexedDBWebSocketscrypto.subtlesetTimeout,setInterval
2. Spawning and Communicating with a Worker
1. The Worker Script (worker.js)
2. The Main Script (app.js)
3. High-Performance Zero-Copy: Transferable Objects
By default, data passed via postMessage() is cloned using the Structured Clone Algorithm (deep copy), which can be slow for 500MB video buffers or typed arrays.
Transferable Objects transfer memory ownership instantly with zero copy ($O(1)$ transfer time). The sender relinquishes ownership:
4. Modern Inline Workers with Blob URLs
When building components with Vite or Webpack, you can create Workers dynamically from string literals:
Practice Quiz
Custom Error Hierarchies & Prototypes
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Async Generators & For-Await-Of | Custom Error Hierarchies & Prototypes |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.