Blog>
Snippets

Web Workers for CPU-Intensive Operations

Offload CPU-intensive tasks to a separate execution context using Web Workers, keeping the main thread free for UI-related tasks.
// main.js - the main thread script
// Check if Web Workers are available
if (window.Worker) {
    // Initialize a new Worker
    const myWorker = new Worker('worker.js');

    // Post data to the worker
    myWorker.postMessage({ message: 'Start the intensive task' });

    // Listen for messages from the worker
    myWorker.onmessage = function(e) {
        console.log('Message received from worker: ', e.data);
    };

    // Listen for errors from the worker
    myWorker.onerror = function(error) {
        console.error('Worker encountered an error: ', error);
    };
} else {
    console.log('Web Workers are not supported in this environment.');
}
This script checks if the browser supports Web Workers and initializes a new worker to handle CPU-intensive tasks. It posts a message to the worker to start the task and listens for messages and errors from the worker.
// worker.js - the script that will run in the worker's thread
// Respond to messages from the main thread
self.onmessage = function(e) {
    console.log('Worker received message: ', e.data);
    // Call a CPU-intensive function
    const result = performIntensiveTask();
    // Post the result back to the main thread
    self.postMessage(result);
};

// A CPU-intensive function (simple example)
function performIntensiveTask() {
    // Simulated heavy computation
    let sum = 0;
    for (let i = 0; i < 1000000000; i++) {
        sum += Math.sqrt(i);
    }
    return sum;
}

// Error handling
self.onerror = function(error) {
    // Post the error back to the main thread
    self.postMessage({ error: error.message });
    // Close the worker
    self.close();
};
This worker script listens for messages from the main thread. Once it receives a message, it performs a CPU-intensive task, in this case, a loop with heavy computation, then sends the result back to the main thread. It also handles errors and can post errors messages back to the main thread before closing itself.