Why HTML5 Web Workers are useful?


JavaScript was designed to run in a single-threaded environment, meaning multiple scripts cannot run at the same time. Consider a situation where you need to handle UI events, query and process large amounts of API data, and manipulate the DOM.

JavaScript will hang your browser in situation where CPU utilization is high. Let us take a simple example where Javascript goes through a big loop:

<!DOCTYPE HTML>
<html>
   <head>
      <title>Big for loop</title>
      <script>
         function bigLoop(){
            for (var i = 0; i <= 10000; i += 1){
               var j = i;
            }
            alert("Completed " + j + "iterations" );
         }
         function sayHello(){
            alert("Hello sir...." );
         }
      </script>
   </head>
   <body>
      <input type = "button" onclick = "bigLoop();" value = "Big Loop" />
      <input type = "button" onclick = "sayHello();" value = "Say Hello" />
   </body>
</html>

On clicking the “Big Loop” button, the following is visible:

The situation explained above can be handled using Web Workers who will do all the computationally expensive tasks without interrupting the user interface and typically run on separate threads.

Updated on: 29-Jan-2020

94 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements