A Web Worker is a JavaScript script that runs in the background, independently of other scripts, without affecting the performance of the user interface. This allows you to perform heavy calculations or data processing without "freezing" the browser window.
Try the two scenarios below. Observe how the spinning circle behaves during the heavy 1-billion iteration loop:
Usually, JavaScript is Single-Threaded, meaning it can only do one thing at a time. If you run a script that takes 5 seconds to finish, the browser cannot react to user clicks or scroll events during those 5 seconds. Web Workers solve this by creating a Background Thread.
First, you need a separate JavaScript file for your worker (e.g., worker.js):
// Inside worker.js
onmessage = function(e) {
let result = e.data[0] * e.data[1];
postMessage(result);
}
Then, in your main HTML file, you create the worker object and listen for messages:
// Main script
let myWorker = new Worker("worker.js");
// Send data to worker
myWorker.postMessage([10, 20]);
// Receive data from worker
myWorker.onmessage = function(e) {
console.log("Result received: " + e.data);
};
If you need to stop a worker immediately, use the terminate() method. This kills the background process and frees up resources.
myWorker.terminate();
myWorker = undefined; // Cleanup
Because they run in a separate thread, Web Workers do **not** have access to several browser features: