JavaScript Notes
Learn JavaScript Web Workers to run CPU-intensive code in background threads without blocking the UI. Covers postMessage, Worker lifecycle, SharedWorker, error handling, and interview Q&A.
JavaScript is single-threaded — all your code, event listeners, DOM manipulation, and rendering share one thread. If a heavy calculation blocks that thread, the entire UI freezes. Web Workers solve this by running JavaScript in a separate background thread, keeping the main thread (and the UI) responsive.
💡 Key insight: Web Workers have no access to the DOM,window, ordocument. They communicate with the main thread exclusively throughpostMessageandonmessage. Think of them as completely isolated workers who can only pass notes back and forth.
How Web Workers Communicate
Data is copied (structured clone algorithm) — not shared. (Except Transferable Objects.)
Creating a Basic Worker
"Sum: 500000500000" // UI remains fully responsive while the worker computes
Inline Workers with Blob URLs
When you can't serve a separate .js file:
"Sorted: [1, 2, 3, 5, 8, 9]"
Two-Way Communication Pattern
"SORTED: [1, 2, 3, 4]" "FILTERED: [2, 4, 6]"
Transferable Objects — Zero-Copy Transfer
By default, data is cloned (copied) when passed to a worker. For large buffers, this is slow. Transferable Objects (like ArrayBuffer) transfer ownership in O(1) time — no copy.
"Before transfer: 52428800" "After transfer: 0" // buffer ownership moved to worker
Terminating a Worker
// From the main thread
worker.terminate();
console.log("Worker terminated");
// From inside the worker itself
self.close();"Worker terminated"
Always terminate workers when they're no longer needed to free memory and CPU.
Error Handling
SharedWorker — Shared Across Tabs
A SharedWorker is shared across all pages from the same origin.
// All open tabs see: "Broadcast: Hello from tab!"
What Web Workers Can and Cannot Access
| Can Access ✅ | Cannot Access ❌ |
|---|---|
fetch() | window object |
IndexedDB | document |
WebSockets | localStorage |
setTimeout/setInterval | DOM elements |
crypto | alert/confirm |
importScripts() | window.location (use self.location) |
navigator (limited) | Canvas 2D (use OffscreenCanvas) |
When to Use Web Workers
- Large array sorting / filtering — avoid freezing the UI
- JSON parsing of massive payloads (e.g., large API responses)
- Image/video processing — pixel manipulation, encoding
- Cryptography — hashing, encryption
- Physics engines — game simulations, collision detection
- Data parsing — CSV processing, markdown compilation, syntax highlighting
Common Mistakes
- Trying to access the DOM inside a worker — throws
ReferenceError. Workers have no DOM. - Not terminating workers — leaving unused workers running wastes memory and CPU.
- Posting large objects without Transferables — cloning 50 MB of data is slow. Use Transferable Objects for
ArrayBuffer,MessagePort,OffscreenCanvas. - Using workers for tiny tasks — the overhead of spawning a worker and message serialization is not worth it for sub-millisecond operations.
- Expecting
localStorageto work in a worker — use IndexedDB instead.
Interview Questions
Q1. What problem do Web Workers solve?
JavaScript is single-threaded. Long computations block the main thread, freezing the UI. Web Workers run code in a separate thread, keeping the main thread free for rendering and user interaction.
Q2. How do the main thread and a worker communicate?
ViapostMessage(data)and theonmessageevent. Data is deep-cloned (structured clone algorithm) when sent, so changes on one side don't affect the other. For large binary data, use Transferable Objects to avoid copying.
Q3. Can a Web Worker access the DOM?
No. Workers have no access towindow,document, or any DOM API. This is by design — DOM manipulation must stay on the main thread to avoid race conditions.
Q4. What are Transferable Objects and why are they useful?
Transferable Objects (like ArrayBuffer) transfer *ownership* to the receiving thread in O(1) time — no copy. After transfer, the original becomes unusable (detached). This is crucial for performance when passing large binary data (e.g., image buffers) to a worker.Q5. What is the difference between a Web Worker and a Service Worker?
A Web Worker is a background computation thread tied to the page lifetime — great for CPU-heavy tasks. A Service Worker is a network proxy that survives page closure — great for caching, offline support, and push notifications. Service Workers have a completely different lifecycle.
Q6. How do you terminate a Web Worker?
From the main thread:worker.terminate(). From inside the worker:self.close(). Always terminate workers when their task is complete.
Q7. When should you NOT use a Web Worker?
When the task is very short (< 1ms), because the overhead of creating a worker and serializing messages exceeds the benefit. Also, don't use workers for DOM manipulation — that's impossible from a worker.
Key Takeaways
- Web Workers run in a separate thread — they cannot access the DOM or
window, but they keep the UI responsive during heavy computation. - Communication is exclusively through
postMessage/onmessage— data is cloned. - Use Transferable Objects (
ArrayBuffer) for large data to avoid expensive copying. - Always call
worker.terminate()when done to free resources. - Use Web Workers for: sorting large arrays, parsing JSON/CSV, image processing, cryptography, physics simulations.
- Use Service Workers for: caching, offline support, push notifications.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Web Workers in JavaScript — Multithreading & Background Tasks Guide.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, browser, apis, web
Related JavaScript Master Course Topics