/    /  HTML Web Workers

HTML Web Workers

 

The Web Workers are the separate JavaScript code that runs in the background of the web page without any affecting the user Interface.

 

What is a Web Worker?

 

Everyone wants a website or application which works fast and can execute multiple operations simultaneously without affecting the performance of the page. However, sometimes we experience some delayed response or degraded performance of the page while executing some large operations. So this problem can be solved using Web Workers.

 

Create a Web Worker File:

 

The simplest way to use web workers is for performing a time-consuming task. generate a simple JavaScript task that counts from 0 to 100,000.

external JavaScript file named “worker.js

 

worker.js:

 

var i = 0;
function countNumbers() {
  if(i < 100000) {
     i = i + 1;
     postMessage(i);
    }

    // Wait for sometime before running this script again
    setTimeout("countNumbers()", 500);
   }
    countNumbers();

 

Tip: The web worker object’s postMessage() method is used to send a message back to the web page from the web worker file.

 

Doing Work in the Background with Web Worker:

 

Generate our web worker file. In this section, we are going to initiate the web worker from an HTML document(file) that running the code within the file named “worker.js” in the background and progressively displays the result on the web page. Let’s see how it works.

 

Example:

 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Using HTML5 Web Workers</title>
<script>
  if(window.Worker) {
     // Create a new web worker
     var worker = new Worker("/examples/js/worker.js");

     // Fire onMessage event handler
     worker.onmessage = function(event) {
      document.getElementById("result").innerHTML = event.data;
    };
  } else{
     alert("Sorry, your browser do not support web worker.");
   }
 </script>
 </head>
 <body>
   <div id="result">
     <!--Received messages will be inserted here-->
   </div>
</body>
</html>

 

OUTPUT:

 

HTML Web Workers

 

Example explained:

 

  • The statement var worker = new Worker(“worker.js”); generates a new web worker object, which is used to communicate with the web worker.
  • When the worker posts a message, it fires the onmessage event handler (line no-14) that allows the code to receive messages from the web worker.

 

Terminate a Web Worker:

 

Start and stop workers from a web page by clicking the HTML buttons. It utilizes the same JavaScript document ‘worker.js‘ what we have used in the previous example to count the numbers from 0 to 100000.

 

Example:

 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Start/Stop Web Worker in HTML5</title>
<script>
  // Set up global variable
  var worker;

  function startWorker() {
    // Initialize web worker
    worker = new Worker("/examples/js/worker.js");

    // Run update function, when we get a message from worker
    worker.onmessage = update;

    // Tell worker to get started
    worker.postMessage("start");
   }

   function update(event) {
     // Update the page with current message from worker
     document.getElementById("result").innerHTML = event.data;
    }

   function stopWorker() {
     // Stop the worker
     worker.terminate();
    }
</script>
</head>
<body>
  <h1>Web Worker Demo</h1>
  <button onclick="startWorker();" type="button">Start web worker</button>
  <button type="button" onclick="stopWorker();">Stop web worker</button>
  <div id="result">
    <!--Received messages will be inserted here-->
  </div>
</body>
</html>

 

OUTPUT:

 

HTML Web Workers