English 中文(简体)
HTML5 - Web Workers
  • 时间:2024-09-17

HTML5 - Web Workers


Previous Page Next Page  

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 utipzation 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" oncpck = "bigLoop();" value = "Big Loop" />
      <input type = "button" oncpck = "sayHello();" value = "Say Hello" />
   </body>
</html>

It will produce the following result −