HTML5 Web Workers

Source: Internet
Author: User

Although there are setinterval and settimeout functions in JavaScript that make JavaScript look as if it makes multithreaded execution, single actually JavaScript makes a single thread, Can only do one thing at a time (about JavaScript single-threaded to see when settimeout () and setinterval () are called to execute), see a simple example to prove

<!DOCTYPE html><Html><Head><Title>web Workers</Title></Head><Body><H1>web Workers</H1><ScriptType= "Text/javascript"> SetTimeout ( () {Console.log (" timeout function ); 1000 "do not Close ' ); </script></body></< Span style= "color: #800000;" >html>           

As soon as the page runs, a dialog pops up, and if SetTimeout is running on another thread, the console will print "Timeout function" in a second, and the fact is that the console will never output text if the dialog box is not closed, and the two words are actually running within a thread.

This design makes JavaScript simple, but sometimes annoying, because the single-threaded design means that the JavaScript code must run out quickly, and the common problem is that a complex JavaScript script breaks the page's other script execution, and even the page loses its response. , which is why the Ajax API is designed to be asynchronous.

Web Workers

The concept of web workers is introduced in the HTML5 specification to solve the problem that client JavaScript cannot be multithreaded, and its defined worker refers to the parallel thread of the code, but the Web worker is in a self-contained environment. The main thread's Window object and the Document object cannot be accessed, and the main thread communication can only pass through the asynchronous messaging mechanism. ("JavaScript authoritative guide")

Web worker

We need to put the JavaScript code that we want to execute separately into a separate JS file, and then call the worker constructor in the page to create a thread, which is the path to the file, and if the argument is a relative address, Then to refer to the script containing the call worker constructor statement, if it is an absolute path, you need to guarantee the same origin (protocol + host + port). This file does not require us to display references on the page using the script tag

var worker=new Worker (' js/worker.js');   

The file is then asynchronously loaded and executed in the background, creating a successful worker that is Jiangzi

We can see that the worker object has only two properties, which is actually a two callback function handle

    1. onerror: When the worker runs out of error and is not caught in the worker, it is captured here
    2. onmessage: When a worker sends a message to the main thread is called

There are two important methods within the prototype.

    1. postMessage: Very familiar with the bright, before we introduced the Window object PostMessage () method, Woker PostMessage method and window is similar, but the parameters are slightly different, Only the message content is passed, and all JavaScript native data types are supported, but it is also possible to serialize to string delivery
    2. Terminate: Terminates worker execution, some workers perform slower, the main thread can actively terminate its execution
A simple small example

In a page display 0~10000 all can be divisible by N of the number, of course, we do not have to i*n this, to slightly make the calculation seems more complicated

Index.html

1<!DOCTYPE html>2<Html>3<Head>4<Title>web Workers</Title>5</Head>6<Body>7<H1>web Workers</H1>89<DivId= "Test"Style= "width:500px;"></Div>10<ScriptType= "Text/javascript">11VarWorker=NewWorker (‘Js/worker.js‘);12Worker.postmessage ({13N:6914});1516Worker.onmessage=function(e) {17Var Test= document.getElementById ( ' test  ' ). Innerhtml=e.data; 18 }; 19 </script>20 </body< Span style= "color: #0000ff;" >>21 </html< Span style= "color: #0000ff;" >>                 

/js/worker.js

Function calc (n) {    var result=[];    for (Var i=1;i<10000; i++) {        var tem=i;        if (i%nif (i% (10*n)tem+= ' <br/>';} result.push (TEM);}} self.postmessage ( Result.join (")); Self.close ();} Onmessage=function (e) {calc (E.DATA.N);};         

It's like a few points.

Worker.onmessage

The message event that binds the main thread, when the worker invokes the PostMessage method, the bound event handler is called to, the data passed can be obtained using the MouseEvent, and the target property can also get the worker object

What is self?

Self is a reference to itself in Woker, some like this

Close ()

The close () method effect is called inside the worker and, like the Terminate () method effect, which invokes the worker instance externally, terminates the worker run

OnMessage

Within the handle, the parameters passed by the external caller are received, and the parameters can be obtained by e.data

Self.postmessage ()

Yes, in this way, we can pass the result to the main thread within the worker, and the handler for the message event bound by the main thread is called

Scope of the worker

This is the simple use of web worker, but some gestures need to be understood.

A new JavaScript environment

When a worker instance is created, it will be in a completely new JavaScript runtime environment, complete and create the worker's foot to leave, even if we pass the message is a reference type they are also copied passed, modify the parameters in the worker does not affect the parameters in the creation script.

Importscripts ()

We can load library functions through a URL in a worker via the Importscripts () method.

Importscripts (' utility/dialog.js ', ' common/cookie.js ');

The method can accept multiple URLs, the URL of the relative address is referenced by the current worker, and the method will download the runtime function sequentially in the order of the parameters, if there is an error in the middle script, the remainder will not be loaded and executed, and the method is synchronous, and only all scripts will be loaded and finished before they are returned.

Worker Execution Model

The worker thread synchronizes its code from top to bottom, then enters the asynchronous phase to respond to the event and timer, and if the worker registers the message event handler, the worker is in memory and does not exit as long as it is likely to fire, but if the worker does not listen for the message, Then when all the tasks have been executed (including the counters), he exits.

What you can use in Web worker

As mentioned earlier, you cannot use the Window object and the Docuemnt object in a worker, so what can I use?

    • Global objects for javascript: JSON, Date (), Array
    • Self reference
    • Location object, but its properties are read-only and are not affected by the caller
    • Navigator Object
    • SetTimeout (), SetInterval () and their corresponding cleaning methods
    • AddEventListener (), RemoveEventListener ()
At last

The Web worker also supports sub workers and shared workers, which is not too carefully looked at, browser compatibility is not ideal, interested students can search the Internet for research.

Excerpt from: http://www.cnblogs.com/dolphinX/p/3452684.html

HTML5 Web Workers

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.