Web Worker javascript multi-threaded programming (1) and worker multi-threaded programming

Source: Internet
Author: User

Web Worker javascript multi-threaded programming (1) and worker multi-threaded programming

What is Web Worker?

Web worker is the JavaScript running in the background. It does not occupy the browser's own thread and is independent of other scripts. It can improve the overall performance of the application and improve the user experience.

Generally, Javascript and UI pages share a thread. When Javascript scripts are executed on HTML pages, the page status cannot respond until the script is completed. This code can be handed over to the Web Worker for running in the background, so the page can still respond to user operations during Javascript running. The background starts a worker thread to execute this code. You can create multiple worker threads.

There are two types of Web Worker

Web workers can be divided into two types: dedicated thread dedicated web worker and shared thread shared web worker. The Dedicated web worker ends with the current page being closed, which means that the Dedicated web worker can only be accessed by the page where it is created. The corresponding Shared web worker can be accessed by multiple pages. In Javascript code, the "Work" type indicates Dedicated web worker, while the "SharedWorker" type indicates Shared web worker.

In most cases, Dedicated web worker is enough, because the code running in web worker is designed for the current page. In some specific situations, web worker may run more universal code and can serve multiple pages. In this case, we will create a Shared web worker for the sharing thread, which can be accessed by multiple associated pages. Only when all associated pages are closed, the Shared web worker ends. Compared with Dedicated web worker, shared web worker is slightly more complex.

The new Worker () object represents Dedicated Web Worker. The following sample code is Dedicated Web Worker.

How to create a Web Worker?

It is very easy to create a new worker. All you have to do is callWorker()Constructor: Specifies the URI of the script to be run in the worker thread. If you want to communicate with the worker and receive the data it passes back, you canonmessageAttribute is set to a specific event handler. When a web worker transmits a message, the code in the event listener is executed. Event. data contains data from worker ..

Example.html: (home page ):

var myWorker = new Worker("worker_demo.js");myWorker.onmessage = function (event) {  console.log("Called back by the worker!\n");};

Alternatively, you can useAddEventListener () adds the event listener:

var myWorker = new Worker("worker_demo.js");myWorker.addEventListener("message", function (event) {  console.log("Worker said : " + event.data);}, false);myWorker.postMessage("hello my worker"); // start the worker.

The first line in the example creates a new worker thread. The third action worker SetsmessageEvent listening function. When worker calls its ownThe postMessage () function calls this event processing function. Finally, the worker thread is started in Row 7.

Note:: InputWorkerThe parameter URI of the constructor must follow the same-source policy.

Worker_demo.js (worker ):

postMessage("I\'m working before postMessage(\'hello my worker\').");onmessage = function (event) {  postMessage("Hi " + event.data);};

Note:Generally, backend threads-including worker-DOM cannot be operated.If the background thread needs to modify the DOM, it should send the message to its creator to complete these operations.

You can do some small-scale distributed computing on the front end, but Web Worker has the following restrictions:

  • Web Worker cannot access DOM nodes;
  • Web Worker cannot access global variables or global functions;
  • Web Worker cannot access global variables and methods of browsers such as windows and document;

However, Web Worker scopes can still be used as follows:

  • Timer-related methods, such as setTimeout (), clearTimeout (), setInterval ()...
  • Navigator object, which contains the following string that can recognize the browser, just as it is done in a common script, such as: appName, appVersion,userAgent...
  • Introduce scripts and libraries, and the Worker thread can access a global function,importScripts()This function allows worker to introduce scripts or libraries into its own scope. You can do this without passing in parameters or passing in the Uris of multiple scripts. The following examples are valid:
    ImportScripts ();/* do not introduce anything */importScripts ('foo. js');/* only introduce "foo. js "*/importScripts ('foo. js', 'bar. js');/* introduce two scripts */
    The browser loads and runs the listed scripts. Global Objects in each script can be used by worker. If the script cannot be loaded, it will throwNETWORK_ERRORThe following code cannot be executed. The previously executed Code (including the code that uses setTimeout for delayed execution) can still be used.importScripts()AfterFunction declaration can still be used, because they will always run before other code.
    Note:The script download sequence is not fixed, but the file name will be passed inimportScripts(). The synchronization is completed until all scripts are downloaded and run,importScripts().
  • Atob () and btoa () base64 encoding and decoding methods.
  • You can also use the XMLHttpRequest object for Ajax communication and other APIs.: WebSocket, Promise, and Worker (Worker can be used in Worker)

 

Terminate web worker

If you want to terminate a running worker immediately, you can call the worker'sThe terminate () method. The terminated Worker object cannot be restarted or reused. We can only create another Worker instance to execute new tasks.

myWorker.terminate();

 

Handling error

When a worker encounters a running error, itsonerrorThe event processing function is called. It will receive an implementationErrorEventInterface NameerrorFor developers to capture error messages. The following code shows how to bind an error event:

worker.addEventListener("error", function(evt){  alert("Line #" + evt.lineno + " - " + evt.message + " in " + evt.filename);  }, false);  

As shown above, the Worker object can be bound to an error event, and the evt object contains the code file (evt. filename), the number of lines of code (evt. lineno), and the error message (evt. message ).

 

The following is a complete dedicated web worker use case.

Demo_worker.html

<!DOCTYPE html>

There is a startWorker button in this HTML page. After you click it, a Javascript file will be run. The code above first checks whether the current browser supports Web Worker. If not, a reminder is displayed.

The Worker object is created in the Click Event of the button, and the Javascript script file demo_workers.js is specified for it (code will be available later), and a "message" event is bound to the Worker object. This event is triggered when the background code (demo_workers.js) returns data to the page. The "message" event can be used to obtain data returned by background code through event. data. Finally, the postMessage method officially executes demo_workers.js, which transmits parameters to the background code. The background code is also obtained through the data attribute of the message event parameter.

Demo_worker.js

addEventListener('message',function (event) {    var count = event.data;    var interval = setInterval(function () {        postMessage(count--);!count && clearInterval(interval);    },1000);});

The above code listens to the message event in the background and obtains the parameters sent from the page. Here is a countdown from 10 to 1: After the message event is triggered, the result is sent to the page for display.

Therefore, when you click the startWorker button, the page will change from 10 to the final 1 in count number: display, and the page will still be able to respond to mouse and keyboard events within 10 seconds. Click the stopWorker button. The web worker is terminated directly, and the page changes are displayed and stopped directly.

 

Embedded web worker

<! DOCTYPE html> 

Now, embedded worker has been nested into a customdocument.workerAttribute.

 

Create a worker in a worker

One advantage of worker is that it can execute processor-intensive operations without blocking the UI thread. In the following example, worker is used to calculate the Fibonacci number.

Fibonacci. js

var results = [];function resultReceiver(event) {  results.push(parseInt(event.data));  if (results.length == 2) {    postMessage(results[0] + results[1]);  }}function errorReceiver(event) {  throw event.data;}onmessage = function(event) {  var n = parseInt(event.data);  if (n == 0 || n == 1) {    postMessage(n);    return;  }  for (var i = 1; i <= 2; i++) {    var worker = new Worker("fibonacci.js");    worker.onmessage = resultReceiver;    worker.onerror = errorReceiver;    worker.postMessage(n - i);  } };

Worker sets PropertiesonmessageSet as a function when the worker object is calledPostMessage () is sent to the function.(Note: This usage is not equivalent to defining a global variable with the same name or a function with the same name.var onmessage Andfunction onmessage The global attributes with the same name will be defined, but they will not register a function that can receive messages sent from the web page that created the worker .) This enables recursion and generates new copies to process every loop of computing.

Fibonacci.html

<!DOCTYPE html>

AdivElement, ID isresult, Use it to display the calculation result, and then generate a worker. After a worker is generated,onmessageThe processing function is configured to pass the settingsdivElement Content to display the calculation result. Finally, send a message to the worker to start it.
Note: chrome does not support creating worker and dump methods in worker, so the above Code can be run in Firefox. Because the article is too long, the introduction to shared thread web worker will be published in the next article.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.