What are Web Workers in JavaScript?
Detailed Explanation
Web Workers allow running JavaScript in background threads, separate from the main UI thread.
Creating a Web Worker:
worker.js:
// Heavy computation
self.onmessage = function(e) {
const { numbers } = e.data;
const result = numbers.reduce((sum, num) => sum + num, 0);
// Send result back
self.postMessage({ result });
};
main.js:
const worker = new Worker("worker.js");// Send data to worker
worker.postMessage({ numbers: [1, 2, 3, 4, 5] });
// Receive result
worker.onmessage = function(e) {
console.log("Result:", e.data.result);
};
// Handle errors
worker.onerror = function(error) {
console.error("Worker error:", error);
};
// Terminate worker
worker.terminate();
Types of Workers:
1. Dedicated Workers - single script
2. Shared Workers - multiple scripts
3. Service Workers - network proxy
Benefits:
- Non-blocking operations
- CPU-intensive tasks
- Parallel processing
- Better user experience
Limitations:
- No DOM access
- Limited API access
- Communication overhead
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts