How to use webworker in JS

Time:2021-10-20
catalogue
  • 1、 Webworker’s initial experience
  • 2、 Common APIs for webworker
    • 1、postMessage(data)
    • 2、terminate()
    • 3、message
    • 4、error
  • 3、 Worker context
    • 4、 About worker

      1、 Webworker’s initial experience

      Therefore, JavaScript is single threaded and has a background.

      As follows:

      <!DOCTYPE html>
          <head>
              <title>singleThread</title>
              <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
          </head>
          <body>
              <script>
                  //Add to the task queue. After the execution of the 'execution stack' where the task to be synchronized is completed, execute this anonymous function in the task queue 1 second later
                  setTimeout(function(){
                      console.log('come on');
                  },1000);
                  //As long as the alert is not closed, the 'execution stack' will not end, so it will not enter the task queue
                  alert('waiting');
              </script>
          </body>
      </html>

      However, HTML5 introduces aWorker (webworker)The concept of. It allows developers to write background programs that can run for a long time without being interrupted by users to execute transactions or logic, and ensure the response of the page to users at the same time.

      In short, JavaScript is allowed to create multiple threads, but the child threads are completely controlled by the main thread and cannot operate on the dom.

      Thus, webworker can be used to process some time-consuming calculations.

      As follows,Main page:

      <!DOCTYPE html>
          <head>
              <title>worker</title>
              <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
              <script>
                  function init(){
                      //Create a worker object and pass it the script URL that will be executed in the new thread
                      var worker = new Worker('worker.js');
                      //Receive data from worker
                      worker.onmessage = function(event){
                          document.getElementById('result').innerHTML+=event.data+"<br/>" ;
                      };
                  };
              </script>
          </head>
          <body onload = "init()">
              <div></div>
          </body>
      </html>

      The following is the content of worker.js:

      var i = 0;
      function timedCount(){
          for(var j = 0, sum = 0; j < 100; j++){
              for(var i = 0; i < 100000000; i++){
                  sum+=i;
              };
          };
          //Send the resulting sum back to the main thread
          postMessage(sum);
      };
      //The time before the execution of timedcount is sent back to the main thread through PostMessage
      postMessage('Before computing, '+new Date());
      timedCount();
      //After the timedcount ends, the end time is sent back to the main thread
      postMessage('After computing, ' +new Date());

      The process executed by the above code is: create a new worker object, use the onmessage method to receive the data (event. Data) passed by PostMessage in worker.js, and append the data to div#result.

      Therefore, the result of executing the above code is as follows:

      Figure I

      After the timedcount method in worker.js completes the operation, execute the PostMessage operation and transfer data to the main thread, as shown in Figure 2. It does not affect the operation of the main thread.

      Figure II

      2、 Common APIs for webworker

      Next, let’s take a look at the common APIs for worker:

      1、postMessage(data)

      The communication between the child thread and the main thread uses the method, and the data passed is an arbitrary value.

      //worker = new Worker('url');
      //Worker.postmessage passes data to child thread, object
      worker.postMessage({first:1,second:2});
      
      //PostMessage can also be used in child threads, such as passing strings
      postMessage(‘test');

      2、terminate()

      The worker is terminated in the main thread and can no longer be used for messaging. Note: once terminated, it cannot be re enabled and can only be created separately.

      
      //worker = new Worker('url');
      worker.terminate();

      For example, main page:

      <!DOCTYPE html>
          <head>
              <title>worker</title>
              <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
              <script>
                  function init(){
                      var worker = new Worker('worker.js');
                      //Every 100 milliseconds, {Name: 'monkey'} information is passed to the child thread
                      setInterval(function(){
                          worker.postMessage({name: 'monkey'});
                      },100);
                      //When the worker of the main thread receives a message from the child thread, the message event is triggered
                      worker.onmessage = function(event){
                          document.getElementById('result').innerHTML+=event.data+"<br/>" ;
                          //The main thread uses the terminate method to interrupt communication with the child thread, and event.data can only be displayed once in the browser
                          worker.terminate();
                      };
                  };
              </script>
          </head>
          <body onload = "init()">
              <div></div>
          </body>
      </html>

      Sub thread worker.js Code:

      //This message event is triggered when the main thread sends a message
      onmessage = function(event){
          //Send event.data.name information to the main thread
          postMessage(event.data.name);
      };

      3、message

      This event is triggered when a message is sent. Moreover, the message sending is bidirectional, and the message content can be obtained through data.

      Message, see the demo in terminate

      4、error

      Error handling. And the error message can be obtained through e.message.

      As follows:

      //worker = new Worker('url');
      worker.onerror = function(e){
          //Print error message
          console.log(e.message);
          //Interrupt the connection with the child thread
          worker.terminate();
      }

      In addition, the worker thread runs its code synchronously from top to bottom, and then enters the asynchronous stage to respond to events and timers. If the worker registers the message event handler, as long as it is possible to trigger, the worker will always be in memory and will not exit. Therefore, after communication, it has to manually terminate in the main thread or close in the sub thread, However, if the worker does not listen for messages, he will exit when all tasks (including counters) are completed.

      3、 Worker context

      Look at the following code first:

      Main page:

      <!DOCTYPE html>
          <head>
              <title>worker</title>
              <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
              <script>
                  function init(){
                      var worker = new Worker('worker.js');
                      //Receive message event
                      worker.onmessage = function(event){
                          console.log(event.data);
                      };
                      //Error message event
                      worker.onerror = function(e){
                          console.log('erro: ' + e.message);
                          //Terminate thread
                          worker.terminate();
                      };
                  };
              </script>
          </head>
          <body onload = "init()">
              
          </body>
      </html>

      worker.js

      //Alert method of window object
      alert(1);
      onmessage = function(event){
          //Send event.data.name information to the main thread
          postMessage(event.data.name);
      };

      Result of executing the above code:

      Why? The reason is that alert is the method of window object, so the error undefined will be reported.

      The context of worker.js execution is different from that of HTML execution on the main page. The top-level object is not window. The global context of woker.js execution is something called workerglobalscope. Therefore, window and window related DOM APIs cannot be accessed, but they can cooperate with setTimeout, setinterval, etc.

      Common properties and methods under the scope of workerglobalscope are as follows:

      1、self

      We can use the self attribute of workerglobalscope to or reference the object itself

      2、location

      The location property returns the workerlocation object associated with the thread when it is created. It represents the absolute URL of the step resource used to initialize the worker thread. Even if the page is reset multiple times, the URL resource location will not change.

      3、close

      Close the current thread, similar to terminate

      4、importScripts

      We can load the library functions in the worker through the URL through the importscripts () method

      5、XMLHttpRequest

      With it, you can make Ajax requests

      6. SetTimeout / setinterval and addeventlistener / PostMessage

      4、 About worker

      What can we do:

      1. You can load a JS to perform a large number of complex calculations without suspending the main process, and communicate through PostMessage and onmessage

      2. You can load another script file through import scripts (URL) in the worker

      3. You can use settimeout(), cleartimeout(), setinterval(), and clearinterval()

      4. You can use XMLHttpRequest to send a request

      5. You can access some properties of navigator

      limitations:

      1. JS cannot be loaded across domains

      2. The code in worker cannot access dom

      3. The implementation of worker in each browser is not consistent. For example, new worker is allowed in worker in FF, but not in chrome

      4. The new feature of IE

      The above is the details of talking about webworker. For more information about talking about webworker, please pay attention to other relevant articles of developeppaer!

      Recommended Today

      Swift advanced (XV) extension

      The extension in swift is somewhat similar to the category in OC Extension can beenumeration、structural morphology、class、agreementAdd new features□ you can add methods, calculation attributes, subscripts, (convenient) initializers, nested types, protocols, etc What extensions can’t do:□ original functions cannot be overwritten□ you cannot add storage attributes or add attribute observers to existing attributes□ cannot add parent […]