HTML5 Web Workers websites can also be implemented with multiple threads

Source: Internet
Author: User

Comments: Web Workers is added in HTML5 to implement background processing in web applications.

Web Workers is added in HTML5 to implement background processing in web applications.

In HTML4, all programs created by js are single-threaded. If it takes a long time, the web interface will not respond for a long time. In the worst case, a script prompt box will pop up:

Indicates whether to continue the script because it takes too long to run .... As a result, the main character of this article is: Web Workers API

Using this API, you can easily create a thread running in the background. It is very easy to create a background program:

The Code is as follows:
Var worker = new Worker ('*. js ');
Note: Background threads cannot access pages or window objects.
Data can be transmitted by sending and receiving messages and background threads:
Worker. onmessage = function (e ){};
Worker. postMessage = function (e ){};

Let's talk about sum:

The Code is as follows:
<! DOCTYPE html>
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> </title>
<Script type = "text/javascript">
Function calculate (){
Var num = 10000000000;
Var r = 0;
For (var I = 1; I <num; I ++ ){
R + = I;
}
Alert (r );
}
Calculate ();
</Script>
</Head>
<Body>
</Body>
</Html>


So I gave the beautiful box... However, web worker does not:

The Code is as follows:
<! DOCTYPE html>
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> </title>
<Script type = "text/javascript">
Var worker = new Worker ('C. js ');
Worker. onmessage = function (e ){
Alert ('And:' + e. data );
};
Function calculate (){
Var num = 1000000;
Worker. postMessage (num );
}
Calculate ();
</Script>
</Head>
<Body>
</Body>
</Html>


The Code is as follows:
Onmessage = function (e ){
Var num = e. data;
Var r = 0;
For (var I = 1; I <num; I ++ ){
R + = I;
}
PostMessage (r );
}

Sometimes I wonder why I have nothing to do with such a big number ..... Of course this is boring, but I want to use it in a scenario.

When I first learned the file api, there was an operation to read local files. If the file is too slow, I don't know if this can be applied? It is necessary to try secondary learning.

Data Interaction with threads

Here we complete a function to randomly generate an array at the front end, and then return the result to the front end after the backend computing can be fully output:

The Code is as follows:
Main Program
<! DOCTYPE html>
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> </title>
<Style>
Span
{
Padding: 10px;
}
</Style>
<Script src = "../jquery-1.7.1.js" type = "text/javascript"> </script>
<Script type = "text/javascript">
$ (Document). ready (function (){
Var worker = new Worker ('T1. js ');
Worker. postMessage ('');
Worker. onmessage = function (e ){
Var arr = e. data. split (';');
For (var I = 0, len = arr. length; I <len; I ++ ){
Var dom = $ ('<span>' + arr [I] + '</span> ');
$ ('# Body'). append (dom );
}
}
});

</Script>
</Head>
<Body>
<Div id = 'body' style = 'width: 400px; word-break: break-all; word-wrap: break-word; '>
</Div>
</Body>
</Html>


The Code is as follows:
Program for generating Arrays
Onmessage = function (e ){
Var arr = [];
For (var I = 0; I <100; I ++ ){
Arr. push (parseInt (Math. random () * 100 ));
}

Var worker = new Worker ('t2. js ');
Worker. postMessage (JSON. stringify (arr ));
Worker. onmessage = function (e ){
// Send the selection result back to the front-end
PostMessage (e. data );
};
}


The Code is as follows:
Determines whether all data in the array is divisible by 3
Onmessage = function (e ){
Var arr = JSON. parse (e. data );
Var str = '';
For (var I = 0, len = arr. length; I <len; I ++ ){
If (parseInt (arr [I]) % 3 = 0 ){
If (str! = '') Str + = ';';
Str + = arr [I];
}
}
PostMessage (str );
Close ();

};

Program Logic description:

Here we use thread nesting.

First, execute the foreground program. Here, a subthread "t1" is initialized to initialize the 100 arrays.

Then, the subthread t1 initializes the subthread t2 (used to traverse the array and retrieve the number that can be divisible by 3 to form a string). t1 transmits the array data to t2

T2 receives t1 data. After calculation, it transfers the string to t1, t1 to the foreground, and the foreground executes its own logic.

Process ended

Conclusion

To put it simply, I declare the sub-thread, send the data to the sub-thread postMessage, and wait for the result to be OK.

Here, combined with the previous communication API Web Sockets, you can combine two Web chat programs, or even use local storage/local database.

This may be a good thing.


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.