Worker in javascript with Example

In JavaScript, a Web Worker is a separate background thread that allows you to perform time-consuming or computationally intensive tasks without blocking the main thread of the web page. This helps to keep the web page responsive and prevents it from becoming unresponsive during resource-intensive operations.

To pass data from the main thread to a Web Worker in JavaScript, you can use the postMessage method. The postMessage method allows you to send data from the main thread to the Web Worker, triggering the worker to process the data asynchronously.

Here’s how you can pass data from the main thread to a Web Worker:

index.html:

<!DOCTYPE html>
<html>
<head>
  <title>Pass Data to Web Worker</title>
</head>
<body>
  <h2>Pass Data to Web Worker</h2>
  <button onclick="startWorker()">Start Worker</button>
  <button onclick="stopWorker()">Stop Worker</button>
  <p id="output"></p>

  <script>
    let worker;

    function startWorker() {
      if (typeof(Worker) !== "undefined") {
        if (typeof(worker) == "undefined") {
          worker = new Worker("worker.js");
        }

        const dataToSend = { num1: 5, num2: 10 };
        worker.postMessage(dataToSend);
        
        worker.onmessage = function(event) {
          document.getElementById("output").innerHTML = event.data;
        };
      } else {
        document.getElementById("output").innerHTML = "Web Workers are not supported in this browser.";
      }
    }

    function stopWorker() {
      worker.terminate();
      worker = undefined;
    }
  </script>
</body>
</html>

worker.js:

// This is the content of the worker.js file.

// Listen for messages from the main thread
onmessage = function(event) {
  const data = event.data;
  const result = doHeavyComputation(data.num1, data.num2);
  postMessage(result); // Send the result back to the main thread
};

function doHeavyComputation(num1, num2) {
  return num1 + num2;
}

In this example, the startWorker function is called when the “Start Worker” button is clicked. Inside this function, we first check if the browser supports Web Workers. If it does, we create a new instance of the Worker object and provide the URL of the worker.js file as an argument. This initializes the Web Worker.

Next, we create an object dataToSend with the properties num1 and num2 representing the data we want to pass to the Web Worker. We then use worker.postMessage(dataToSend) to send this data to the Web Worker.

In the worker.js file, we use the onmessage event handler to listen for messages sent from the main thread. When a message is received, we can access the data sent with the message using event.data. In this example, we extract num1 and num2 from the received data object and pass them as arguments to the doHeavyComputation function. The computed result is then sent back to the main thread using postMessage.

Once the computation is complete, the onmessage event handler in the main thread receives the result and updates the output element to display the computed value.

By using postMessage, you can efficiently communicate and transfer data between the main thread and the Web Worker, allowing for background processing without blocking the main thread and maintaining a responsive user interface.

Leave a Comment