Using Web Workers to Offload Heavy Computations in JavaScript

Learn how to use Web Workers in JavaScript to run heavy computations in the background, keeping your web app responsive.

When building web applications, running heavy tasks like complex calculations can freeze the user interface, making the app feel slow or unresponsive. Web Workers allow us to run such tasks in the background, off the main thread, so the UI stays smooth.

In this tutorial, you'll learn how to create a simple Web Worker that calculates a large Fibonacci number without blocking the main UI thread.

### What are Web Workers? Web Workers are a way to run JavaScript in background threads. They do not have access to the DOM but can communicate with the main script via messages.

### Step 1: Create a Worker Script Create a separate JavaScript file called `worker.js`. This file will contain the code that runs inside the worker.

javascript
self.onmessage = function(event) {
  const n = event.data;

  function fibonacci(num) {
    if (num <= 1) return num;
    return fibonacci(num - 1) + fibonacci(num - 2);
  }

  const result = fibonacci(n);

  // Post the result back to main thread
  self.postMessage(result);
};

### Step 2: Using the Worker in Your Main Script Now, let's create the main script file (e.g. `main.js`) where you start the worker and listen for messages from it.

javascript
const worker = new Worker('worker.js');

// Send data to the worker
worker.postMessage(40);  // Calculate the 40th Fibonacci number

// Listen for messages from the worker
worker.onmessage = function(event) {
  console.log('Fibonacci result:', event.data);
  alert('Fibonacci result: ' + event.data);
};

// Optional: handle worker errors
worker.onerror = function(error) {
  console.error('Worker error:', error.message);
};

### Step 3: Putting It All Together in HTML Finally, you can create a simple HTML page to test this setup.

javascript
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Web Worker Demo</title>
</head>
<body>
  <h1>Web Worker Fibonacci Calculator</h1>
  <button id="startBtn">Start Calculation</button>

  <script src="main.js"></script>
  <script>
    const startBtn = document.getElementById('startBtn');
    const worker = new Worker('worker.js');

    worker.onmessage = function(event) {
      alert('Fibonacci result: ' + event.data);
      startBtn.disabled = false;
    };

    worker.onerror = function(error) {
      console.error('Worker error:', error.message);
      startBtn.disabled = false;
    };

    startBtn.addEventListener('click', () => {
      startBtn.disabled = true;
      // Calculate 40th Fibonacci number
      worker.postMessage(40);
    });
  </script>
</body>
</html>

### Summary You have learned how to use Web Workers to run heavy computing tasks without freezing your web page. This technique makes your applications feel faster and more responsive. Try adapting Web Workers for other long-running tasks like image processing or data parsing!