Multithreading in "Worker" JS

Source: Internet
Author: User
Tags button type

Because the next project to use some of the countdown function, so prepared in advance, the province will be the time when the interface is unfriendly and some other things. Just take advantage of this opportunity to deepen the usage and understanding of multithreaded workers in HTML5.

Worker profile

The JavaScript language uses a single-threaded model, which means that all tasks can only be done on one thread at a time. The task ahead is not finished, and the task behind it can only wait. These are all known to us. But as the business continues to grow, simply single-threaded patterns may not be able to meet our needs. The background task worker API was added to the HTML5.

Introduction: Web Worker is a JavaScript running in the background, independent of other scripts, does not affect the performance of the page. You can continue to do anything you want to do: Click, select Content, and so on, while the Web worker runs in the background.

The worker is creating a multithreaded environment for JavaScript, allowing the main thread to create worker threads and assigning some tasks to the latter to run. Open a background thread and do some time-consuming or asynchronous operations without affecting the foreground thread. Because it is a different thread, the main thread does not interfere with the worker thread. And they don't interrupt each other. So in some scenarios can improve the flow of the page. Once a worker thread has been created successfully, it will always run and will not be interrupted by activities on the main thread, such as a user clicking a button or submitting a form. This facilitates communication at any time in response to the main thread. However, this also causes the Worker to be more resource-intensive, should not be overused, and should be closed once it is used.

Usage rules
    1. Must be homologous: that is, the path of the JS file must be the same as the main thread script. External references are prevented.
    2. Dom restriction: Dom (document,window,parent) cannot be manipulated in worker threads. Note You can use the browser's navigator and location objects.
    3. Communication restrictions: The worker thread and the main thread are not in a context so they cannot communicate directly. This means that the variables defined by the main thread are not available in the worker. All can only be done by message.
    4. Hint Forbidden: Worker thread cannot alert and confirm, this does not know the specific reason?
    5. The value of the DOM: Message communication is also not possible to pass a value DOM can only be a variable.
    6. IE Restrictions: IE9 cannot be used! IE9 cannot be used! IE9 cannot be used!
Worker documentation

The interface of the Worker Web Workers API represents a background task that can be easily created to send a message back to its creator. Creating a worker is as simple as calling a constructor and specifying a script to run in a worker thread.

constructor function

worker (): creates a dedicated web worker that executes a script on the specified URL. Example: Var worker=new worker (' js/settime.js ');

Properties

OnError

This is a function that is called when the error event occurs and bubbles the worker through the function. Example: Worker.onerror=function () {...};

onmessage:

This is the event that is called when a message event in a worker is about to occur. Example: Worker.onmessage=function () {...};

This event is typically used in conjunction with the PostMessage event, one for sending data and one for receiving data. For example:

In the main thread:

  var jsid = "00001";   var New Worker (' js/settime.js ');  Worker.postmessage (JSID);

In the worker thread:

// Accept Event Arguments function (e) {    console.log (e.data[0])}

This completes a process where the main thread passes parameters to the worker thread. Also if the worker thread is going to pass parameters to the main thread in turn.

Onmessageerror:

An incorrect property event occurred during the message delivery process. Example: Worker.onmessageerror=function () {...};

Method

PostMessage:

Sends a message to the internal scope of the thread worker, which can set parameters and send data to the worker thread. Accepted in the OnMessage.

Terminate

Too many open worker threads waste resources so you can terminate it after use, and the terminating method uses terminate (). Example: Worker.terminate ();

Close

In addition to the above closure, if the worker thread itself can also use Self.close () to close.

Timer example

It says so much about the use of some of the basic properties or methods of the worker. Here's an example of how the effect looks.

Let's take the most common countdown to illustrate the example. A very simple example. We often encounter countdown business in the business, and in the countdown to do some other business. Because of the JS single-threaded feature, you will find that your countdown is paused while you are doing other business operations. For example now it is 9:57 you have done three seconds of business processing. And so the business processing should be completed: 9:54, but your countdown is still 9:57. This phenomenon is clearly illustrated.

Scene Business Design

So now we're designing such a business operation,

    • First, our page has a timer and a business Operation button (to simulate time-consuming operations).
    • The timer is then written to a worker to perform a countdown operation.
    • Finally, each countdown time is sent to the main thread through message communication so that the main thread modifies the display time.
    • End countdown Complete Timer and thread

One might say why go back to the main thread to modify the time display value, please look at the above usage rules, I was also intended to carry out the main line path value DOM to the worker thread but not only in return.

Code Show

HTML code:

<body>        <div>            <span id= "minute_p" >10</span>:            <span id= "Second_p" >00< /SPAN>        </div>        <button type= "button" onclick= "Business ()" > Time-consuming Operation </button>
</body>

Main thread JS code:

            //Initialize after page load is completeWindow.onload =function() {                //Creating a Timer thread                varWorker =NewWorker (' Js/settime.js '); //get DOM Object                vardomminute_p = document.getElementById (' minute_p ')); vardomsecond_p = document.getElementById (' second_p ')); Worker.postmessage (600); //The return value of the worker thread can be accepted hereWorker.onmessage =function(event) {varTotalsecond =Event.data; Console.log (Totalsecond)//Count the number of minutes                    varMinute_p = parseint (totalsecond/60); Domminute_p.innertext=minute_p; //calculate the number of seconds                    varsecond_p = parseint (totalsecond% 60); Domsecond_p.innertext=second_p; }            }            //This is a simulated time-consuming operation.            functionBusiness () {vardata = [1, 2, 3, 4, 5];  for(vari = 1; i < 1000; i++) {                     for(varj = 1; J < 1000; J + +) {                         for(varK = 1; K < 5000; k++) {                            varb = k * 100; }}} console.log ("The business is finally gone!" ")            }

Worker thread JS Code:

var totalsecond = +; var domminute_p, domsecond_p,     // Accept event Arguments    function (e) {        console.log (e.data)        = e.data;    } var timeid = setinterval (function() {    Totalsecond--;     if (Totalsecond = = 0) {        self.close ();    }    Console.log (Totalsecond)    1000)

Okay, so much for the rough example. Here are the effects:

Start running after the number 1 will start the countdown, but when you click on the number 2 for the simulation time-consuming, the number 1 will still be stuck, only the completion of the number 2 will not run, but different with the above mentioned single-threaded is, he again run the time is the correct time, or just the example if it is 9 : 57, click Number 2 The simulation takes 3 seconds, and the time-consuming completion number 1 displays 9:54 instead of single-threaded 9:57. This means that the worker is now running in time-consuming operation, and the time card is just the main thread of the DOM operation is stuck (can be time-consuming business also open the worker will not get stuck). This is just to introduce the use of the worker, all do not struggle with this interface display problems.

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.