Handling CPU-bound tasks with Web Workers in JavaScript allows you to offload heavy computations from the main thread, preventing it from becoming unresponsive. Here's a step-by-step guide on how to do this:
-
Create a Web Worker File:
Create a new JavaScript file for your Web Worker, for example,
worker.js
. This file will contain the code that performs the CPU-bound task.// worker.js self.onmessage = function(event) { // Receive data from the main thread const data = event.data; // Perform CPU-bound task const result = cpuIntensiveTask(data); // Send the result back to the main thread self.postMessage(result); }; function cpuIntensiveTask(data) { // Implement your CPU-bound task here // Example: Calculate Fibonacci sequence function fibonacci(n) { return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); } return fibonacci(data); }
-
Create a Web Worker Instance in Your Main Script:
In your main script (e.g.,
main.js
), create a new Web Worker instance using theWorker
constructor, passing the path to the Web Worker file.// main.js const worker = new Worker('worker.js');
-
Send Data to the Web Worker:
You can send data from the main thread to the Web Worker using the
postMessage
method.const inputData = 40; // Example input data worker.postMessage(inputData);
-
Receive Result from the Web Worker:
Listen for messages from the Web Worker using the
onmessage
event handler.worker.onmessage = function(event) { const result = event.data; console.log('Result:', result); };
-
Terminate the Web Worker (Optional):
After you have received the result from the Web Worker, you can terminate it using the
terminate
method.worker.terminate();
Putting it all together:
// main.js
const worker = new Worker('worker.js');
const inputData = 40;
worker.postMessage(inputData);
worker.onmessage = function(event) {
const result = event.data;
console.log('Result:', result);
worker.terminate(); // Terminate the worker after receiving the result
};
// worker.js
self.onmessage = function(event) {
const data = event.data;
const result = cpuIntensiveTask(data);
self.postMessage(result);
};
function cpuIntensiveTask(data) {
function fibonacci(n) {
return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);
}
return fibonacci(data);
}
With this setup, the CPU-bound task (calculating the Fibonacci sequence in this example) will run in the background without blocking the main thread, ensuring a smooth user experience.