index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
<!DOCTYPE html>
<
html
>
<
body
>
<
p
>Count numbers: <
output
id
=
"result"
></
output
></
p
>
<
button
onclick
=
"startWorker()"
>Start Worker</
button
>
<
button
onclick
=
"stopWorker()"
>Stop Worker</
button
>
<
br
/><
br
/>
<
script
>
var w = null;
function startWorker(){
if(typeof(Worker)!=="undefined"){
if(w==null){
w=new Worker("worker.js");
}
w.onmessage = function (event) {
document.getElementById("result").innerHTML=event.data;
};
}
else{
document.getElementById("result").innerHTML="Sorry, your browser does not support Web Workers...";
}
}
function stopWorker(){
if(w==null){
return;
}
w.terminate();
w = null;
}
</
script
>
</
body
>
</
html
>
|
worker.js
1
2
3
4
5
6
7
8
9
|
var
i=0;
function
timedCount(){
i=i+1;
postMessage(i);
setTimeout(
"timedCount()"
,500);
}
timedCount();
|
本文转自 antlove 51CTO博客,原文链接:http://blog.51cto.com/antlove/1673635