Concept Explanation
JavaScript is single-threaded, but Web Workers let you "Hire an Assistant." A Worker is a script that runs in a completely separate thread. This means it can do heavy math for 10 seconds, but your main website stays fast and smooth.
The Assistant (Worker) and the Boss (Main Thread) talk to each other by sending Messages.
Syntax or Core Structure
1. The Main Script
const assistant = new Worker("heavy_logic.js");
assistant.postMessage("Calculate Pi!");
assistant.onmessage = (e) => {
console.log("Assistant says: " + e.data);
};
2. The Worker Script (heavy_logic.js)
onmessage = (e) => {
// Perform heavy math here...
postMessage(3.14159);
};
Limitations
- No DOM Access: Workers CANNOT touch the DOM. They can only crunch numbers and return the result.
- No Windows: Workers don't have access to
window,document, orlocalStorage. - Same-Origin: You can only load workers from your own domain.
Common Mistakes
- Sending Functions: You can only pass data (strings, numbers, plain objects) through
postMessage— never functions or DOM nodes. The data is copied, not shared. - Worker Overkill: Spinning up a Worker has a real startup cost. Don't hire an assistant to add
2 + 2. Reserve them for genuinely heavy loops. - Leaking Workers: A Worker runs forever until you call
terminate()or the page unloads. Forgotten workers quietly drain memory and battery.
Best Practices
- Keep It Pure: Treat a Worker like a math function — data in, result out, no side effects.
- Batch Your Messages: Crossing the thread boundary is slow. Send one big array, not 10,000 tiny pings.
- Feature Detect: Wrap usage in
if (window.Worker)so ancient browsers degrade gracefully instead of crashing.
Practice Exercises
- The Prime Finder: Use a Worker to calculate the 5000th prime number. Press buttons on the main page while it's working to prove it doesn't freeze.
- The Data Cruncher: Pass a massive array (100k items) to a worker, have it sort it, and pass it back.
- The Terminater: Research
worker.terminate()and explain when you would use it to save battery life.