There is no doubt that javascript. There is no multi -threaded saying. He can only do one thing one thing, do one thing and do the next thing. In a matter, the browser will be stuck for a while and does not respond to the user's operation. What should I do? Thanks, HTML5 provides us with a multi -threaded mechanism. Such a good thing, presumably you have used it again, but it doesn't matter, let's review it one by one!
1. Worker class 1. Method introduction(1) Constructing function NEW WORKER (ARG): The parameter represents the JS file where the code you want to execute, such as 'myWorker.js', and the constructor is of course returning an instance of a worker class
(2) WORKER.POSTMESSAGE (MESSAGE): This method indicates that sending messages from the main thread to sub -threads or sub -threads send messages to the main thread.
(3) There is also a Message event on the worker. When someone sends a message to this worker instance, the incident is triggered.
You can see that the API of the WOKER class is quite concise. There are only two most commonly used methods, one event, let's take a look at the actual examples below.
//main.html<!!!! <html lang = EN> <Head> <meta charset = UTF-8> <Title> Main </title> </head> <body> </head> </head> </head> <div ID = OUT> </ DIV> <input Type = Text name = ID = TXT> <Button ID = BTN> Send </Button> <Script Type = Text/Javascript> VAR OUT = DOCUMENT.GetelementByid (Out); VAR B tn = document.GetelementByid (BTN ).; .postmessage (postdata);}, false );; 'Message', Function (E) {Out.Innertext = E.Data; FALSE); </script> </html> // Thread1.jsonMessage Tion (EVENT) {var res = event.data+handsome! ; PostMessage (res);}
When I enter the text box large ~ bear click the sending button, there will be the following effect
Simple analysis and analysis, I created a worker instance worker on the main thread by Trip1.js. When you click the button, I will call his postmessage method to send the contents of the text box to Thread1.js. How to do our thread1.js do What about it? Yes, he listened to the MESSAGE incident. The main thread sent a message to trigger the event, execute the callback function, the callback function obtained the value sent from the event object, and then add this value to handsome! , Then send it back. The main thread also listened to the MESSAGE event of Worker, so the message will be triggered in the past, and the message content is displayed in DIV, so that the above effect is seen.
Maybe you will use this? It is really useless here. Here we can always complete the handsomeness on the main thread! Operation, because his complexity is O (1) (haha, he is studying algorithms recently!), But if it wasn't for such a simple operation? The advantage of this method is that how complicated your sub -threads do, you will not stop the main thread. Why do the main thread change? When the sub -thread is processed, he will take it directly. Essence
Teacher Lu will be able to call New Worker () to create a new sub -thread in the sub -thread. I find that this is not possible. I will report the UNDEFINED error. That is to say I was wrong. Later, I checked the official document and found that there was no relevant description.
Let's look at an example of calling multiple sub -threads on the main thread:
//main.html<!!!! <html lang = EN> <Head> <meta charset = UTF-8> <Title> Main </title> </head> <body> </head> </head> </head> <div ID = OUT> </ DIV> <input Type = Text name = ID = TXT> <Button ID = BTN> Send </Button> <Script Type = Text/Javascript> VAR OUT = DOCUMENT.GetelementByid (Out); VAR B tn = document.GetelementByid (BTN );; Var worker1 = new worker (thread1.js); var worker2 = new worker (thread2.js); on () {var postdata = txt.value ; worker1.postmessage (postdata);}, false); worker1.addeventListener ('message', function (e) {worker2.postmessage (e.Data);}, FALSE); worker2. addeventristener ('message', function e) {out.Innertext = E.Data;}, FALSE); </script> </body> </html> // Thread1.jsonMessage = Function (EVENT) {var res = event.data+handsome! ; PostMessage (res);} // Thread2.jsonMessage = Function (Event) {var res = event.data+not lied to you! ; PostMessage (res); close ();}
The main thread requires two threads to complete one task. It creates two thread WORKER1,2, first requested from Worker1, after getting the returned data, then requesting worker2, at the same time handed the data after worker1 to Worder2 processing, and then take it with To the final result, it is displayed on the page.
Other JS files can be introduced in sub -threads and then called, such as the example of the lower side.
//main.html<!!!! <html lang = EN> <Head> <meta charset = UTF-8> <Title> Main </title> </head> <body> </head> </head> </head> <div ID = OUT> </ DIV> <input Type = Text name = ID = TXT> <Button ID = BTN> Send </Button> <Script Type = Text/Javascript> VAR OUT = DOCUMENT.GetelementByid (Out); VAR B tn = document.GetelementByid (BTN );; Var worker1 = new worker (thread1.js); btn.addeventristener (click, function () {var postdata = txt.value; work Er1.postmessage (Postdata);}, FALSE );; 'Message', Function (E) {Out.Innertext = E.Data; FALSE); </script> </html> 'Tools.js ') OnMessage = Function (Event) {var res = handler (event.data); postmessage (res);} // Tools.jsFunction handler (data) {Return Data+Come on! }
It can be seen that our Thread1.js does not have a file called Tools.js, but it imports a js file through importscripts (), and then you can call the exposed method.
Second, SharedWorker classThe essence of SharedWorker lies in Share. Different threads can share a thread, and their data is also shared.
Direct examples to discuss.
How to use one://main.html<!!!!! <Head> <Title> Shared Workers: Demo 1 </Title> </Head> <body> <DIV ID = LOG> </DIV> <Script> var worker = New SharedWorker ('shared.js'); var log = document.GetelementByid ('log'); worker.Port.onMessage = Function (E) {// not workr.onMessage! Log.textContent = '/n' + E.Data;} </script> </body> </html> // shared.jsonconnect = function (e) {var port = e.ports [0]; port.postmessage ('hello world!');}
This is an example from the W3C. Let's look at the second method first, and then make an analysis
<! Doctype html> <html> <gead> <Title> Shared Workers: Demo 2 </Title> </Head> <body> <DIV ID = LOG> </DIV> <Script> var worker = New SharedWorker ('' ' shared.js'); Var log = document.GetelementByid ('log'); worker.port.addeventristener ('message', functionage (e) {log.textContent + = '/n' + e. data;}, false );; // Note: Note: Need this when used addeventListener worker.Postmessage ('ping'); </script> </body> </html> // sharedonConnect = f unction (e) {var port = e.ports [0]; port.postmessage ('hello world!'); port.onMessage = Function (e) {port.postmessage ('pong'); // not e.ports [0]. PostMessage! // E.Target.postmessage ('Pong'); Would Work Also}}}
The first method is to listen to the Message event by using the event handle. There is no need to call worker.port.start (). Active port. They are different from Worker. When someone communicates with him, the Connect event is triggered, and then his Message event is bound to the MESSAGEPORT object. If you don't want Worker, you can look back to see how workers do it.
So how does SharedWorker share data? Please look at the following example.
// main1 and main2 are so <! Doctype html> <html> <wead> <Title> Shared workers: Demo 2 </Title> </Head> <body> <div ID = log> </div> <input Type = Text name = ID = TXT> <Button ID = get> get </Button> <Button ID = SET> Setton> <Script> Var worker = new shared worker ('shared.js'); VAR GET = DOCUMENT.GetelementByid ('get'); var set = document.GetelementByid ('set'); var txt = document.GetelementByid ('txt'); TelementByid ('Log'); worker.Port.addeventListener ('Message', Function (E) {log.innertext = e.data;}, false); worker.port.start (); // not: need this when using addeventListener ( 'Click', Function ( e) {worker.port.postmessage (txt.value);}, false); get.addeventListener ('click', function (e) {worker.Postmessage); ); </ script> </body> </html> // sharedvar data; onconnect = function (e) {var port = e.ports [0]; port.onMessage = function (e) {if (e.data == 'Get ') {port.postmessage (data);} else {data = e.data;}}}
Analysis here, we enter data in the text box of main1.html, click SET, and then click the get method in main2.html to get the data we set in main1.html Single cases, just like the Static class in Java, no matter how many news, there is actually only one, so that our different threads can share data in Sharedworker. Here is the picture. Remember that there was an article without a picture, and someone gave me suggestions and asked if he could give the picture.
Finally, let's summarize, worker and SharedWorker have no hanging, that is, move the work in front of the stage to do it behind the scenes without interrupted the work in front of the stage. It is the so -called ten minutes on the stage and ten years off the stage. If you put the ten years off the stage to the stage, the audience's saliva star has already drowned you, so it is said that those laborious jobs are still put Going down, only the best side of your best side is on the stage, ten minutes is enough!