Blog>
Snippets

Using Web Workers for CPU-Intensive Tasks

Explain how to offload heavy data processing to a Web Worker to prevent blocking the main thread, keeping the UI responsive.
// This is the main script file
if (window.Worker) {
    const worker = new Worker('worker.js');

    // Send data to the worker
    worker.postMessage('Start processing');

    // Receive results from the worker
    worker.onmessage = function(e) {
        console.log('Message received from worker', e.data);
    };

    // Listen for errors from the worker
    worker.onerror = function(error) {
        console.error('Error occurred in worker:', error);
    };
} else {
    console.error('Web Workers are not supported in your browser.');
}
In the main JavaScript file, we check for Web Worker support and create a new worker thread using worker.js file. We then post a message to the worker to start processing and set up handlers for messages and errors coming back from the worker.
// This is worker.js - the Web Worker file
self.addEventListener('message', function(e) {
    // Heavy data processing happens here
    const result = heavyDataProcessing(e.data);
    // Post the result back to the main thread
    self.postMessage(result);
});

function heavyDataProcessing(data) {
    // Simulate heavy processing with a loop
    let result = 0;
    for (let i = 0; i < 1000000; i++) {
        result += i;
    }
    return result;
}

self.addEventListener('error', function(error) {
    // Handle any errors that occur within the worker
    self.postMessage('An error occurred: ' + error.message);
    self.close(); // Terminate the worker
});
Inside worker.js, we add event listeners to respond to messages from the main thread. Here the heavyDataProcessing function is a placeholder for actual CPU-intensive tasks. Once the heavy processing is completed, the result is posted back to the main thread. An error listener is also set up to handle any errors in the worker thread.