Web Worker is an API provided by HTML5 that allows the creation of background threads in the browser environment, thereby implementing multithreaded processing of web applications. Since JavaScript is executed in a single thread by default on the browser side, long-running calculations, big data processing, intensive computing and other tasks may cause the user interface to freeze or become unresponsive if they are not properly separated. Web Worker can perform these tasks without affecting the main thread (i.e., UI thread) by creating independent worker threads, thereby improving the user experience.
Basic use of Web Worker
- Create a Worker: Use new Worker(url) to create a Worker instance, where url is the URL containing the Worker script.
- Communication:
- The main thread sends a message to the Worker: Use the worker.postMessage(data) method, where data can be any serialized JavaScript value.
- The Worker sends a message to the main thread: Use self.postMessage(data) in the Worker script.
- Receive messages:
- Main thread: Process messages from the Worker by listening to the worker.onmessage event.
- Worker: Use self.addEventListener(‘message’, handler) in the Worker script to add a message handler.
- Lifecycle management:
- Start: Create a Worker instance to start the thread.
- Terminate: Call the worker.terminate() method to stop the Worker thread.
Example
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Web Worker Example</title>
</head>
<body>
<button onclick="startWorker()">Start Worker</button>
<button onclick="stopWorker()">Stop Worker</button>
<div id="result">Result: Loading...</div>
<script>
let myWorker;
function startWorker() {
if (!window.Worker) {
alert("Your browser does not support Web Workers.");
return;
}
myWorker = new Worker('worker.js');
myWorker.onmessage = function(e) {
document.getElementById('result').textContent = 'Result: ' + e.data;
};
myWorker.postMessage([1, 2, 3, 4, 5, ...Array(1000000).fill(0).map((_, i) => i + 6)]);
}
function stopWorker() {
if (myWorker) {
myWorker.terminate();
myWorker = null;
document.getElementById('result').textContent = 'Result: Worker stopped';
}
}
</script>
</body>
</html>Worker Script(worker.js):
// This code runs in a separate thread
self.addEventListener('message', function(e) {
const numbers = e.data;
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
self.postMessage(sum);
}, false);In this example:
- When the user clicks the “Start Worker” button, a new Web Worker instance is created, pointing to the worker.js script.
- A large array containing a lot of numbers is sent to the Worker.
- After the Worker receives the message, it calculates the cumulative sum of the array.
- After the calculation is completed, the Worker sends the result back to the main thread via postMessage.
- After the main thread receives the message, it updates the page to show the result.
- When the user clicks the “Stop Worker” button, the Worker thread is terminated.



