HTML Web Workers API

    HTML Web Worker API is a JavaScript code that runs in the background and does not affect the page performance.

    Web Workers

    When the <script> or JavaScript code executes then only the page become responsive. A web worker runs in the background independent of the other script without affecting the page performance. Web workers make the page more alive and responsive, it makes sure that a specific JavaScript code gets executed according to the user interaction. To create a worker, we use the Worker() constructor and pass a JavaScript file to it. That JavaScript file contains the main code that will run in the background.

    Example

    Make a counter using worker:

    <!DOCTYPE html>
    <html>
    <body>
    
    <p>Counter: <output id="result"></output></p>
    <button onclick="start()">Start </button> 
    <button onclick="stop()">Stop </button>
    
    <script>
    var w;
    
        function start()
        {
             if(typeof(Worker) !== "undefined") {
                if(typeof(w) == "undefined")
                  {
                      w = new Worker("counter.js");
                  }
               w.onmessage = function(event) 
                  {
                   document.getElementById("result").innerHTML = event.data;
                  };
                } 
              else {
                document.getElementById("result").innerHTML = 
                "Browser Does not Support";
                   }
          }
    
        function stop() { 
           w.terminate();
           w = undefined;
           }
        </script>
    
    </body>
    </html>

    #counter.js

    var i = 0;
    
    function timedCount() {
      i = i + 1;
      postMessage(i);
      setTimeout("timedCount()",500);
    }
    
    timedCount();

    <Note>: Before we create a web worker, we should check whether the browser supports it or not.

    Create a Web Worker Object:

    To create a web worker object, we use the Worker() constructor and specify the JavaScript file as a parameter for the thread execution.

    w= new Worker("counter.js");
    

    The counter.js file contains the code which will process in the background.

    var i = 0;
    
    function timedCount() {
      i = i + 1;
      postMessage(i);
      setTimeout("timedCount()",500);
    }
    
    timedCount();

    Terminate

    The web worker object keeps listing the message until it gets terminated. To terminate the worker, we use the terminate() method.

    function stop() 
    { w.terminate(); 
    w = undefined; 
    }

    Summary

    • Web worker is a JavaScript code that runs at the background.
    • Web workers are external files so they can not access the window, document and parent objects.
    • It is necessary to terminate the worker object.

    People are also reading: