亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

HTML5 Web Workers

Web Workers

The concept of web workers is introduced in the html5 specification to solve the problem that client-side JavaScript cannot be multi-threaded. The worker defined refers to the parallel thread of the code, but the web The worker is in a self-contained environment and cannot access the window object and document object of the main thread. It can only communicate with the main thread through the asynchronous message passing mechanism

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. The parameter is the file path. If the parameter storage is a relative address, then the script containing the statement that calls the Worker constructor should be used as a reference. If it is an absolute path, It is necessary to ensure the same origin (protocol + host + port). This file does not require us to use script tags to display references on the page

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

Simple Small example

Display all the numbers from 0 to 10000 that can be divisible by n on a page. Of course, we don’t use i*n to make the calculation a little more complicated

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Web Workers</title>
</head>
<body>
  <h1>Web Workers</h1>
      <div id="test" style="width:500px;"></div>
    <script type="text/javascript">
        var worker=new Worker('js/worker.js');
        worker.postMessage({
            n:69
        });
        worker.onmessage=function(e){
            var test=document.getElementById('test').innerHTML=e.data;        
        };
    </script>
</body>
</html>

/js/worker.js

function calc(n){
    var result=[];
    for(var i=1;i<10000;i++){
        var tem=i;
        if(i%n==0){
            if(i%(10*n)==0){
                tem+='<br/>';
            }
            result.push(tem);
        }
    }

    self.postMessage(result.join(' '));
    self.close();
}

onmessage=function(e){
    calc(e.data.n);
};

Display effect:

1018.png

Create web worker file

Now, Let's create our web worker in an external JavaScript.

Here we create the counting script. The script is stored in the "demo_workers.js" file:

var i=0;

function timedCount()
{
i=i+1;
postMessage(i);
setTimeout("timedCount()",500);
}

timedCount();

The important part of the above code is the postMessage() method - it is used to pass a message back to the HTML page.

Note: web workers are usually not used for such simple scripts, but for more CPU-intensive tasks.

Create Web Worker Object

We already have the web worker file, now we need to call it from the HTML page.

The following code detects whether the worker exists. If not, - it creates a new web worker object and then runs the code in "demo_workers.js":

if(typeof (w)=="undefined")
{
w=new Worker("demo_workers.js");
}

Then we can happen from the web worker and Received the message.

Add an "onmessage" event listener to the web worker:

w.onmessage=function(event){
document.getElementById("result").innerHTML= event.data;
};

<pWhen web="" worker="" delivers a message, the code in the event listener is executed. event.data="" contains data from ="" event.data="".

Terminate Web Worker

After we create the web worker object, it will continue to listen for messages (even after the external script completes) until its until terminated.

To terminate the web worker and release browser/computer resources, please use the terminate() method:

w.terminate();




Continuing Learning
||
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <!-- web worker是運行在后臺的javascript,不會影響頁面的性能 --> <p>計數(shù):<output id="result"></output></p> <button onclick="startWorker()">開始worker</button> <button onclick="endWorker()">停止worker</button> <br><br> <script type="text/javascript"> var w; function startWorker(){ if(typeof(Worker)!="undefined"){//瀏覽器支持web worker if(typeof(w)=="undefined"){//w是未定義的,還沒有開始計數(shù) w = new Worker("webworker.js");//創(chuàng)建一個Worker對象,利用Worker的構造函數(shù) } //onmessage是Worker對象的properties w.onmessage = function(event){//事件處理函數(shù),用來處理后端的web worker傳遞過來的消息 document.getElementById("result").innerHTML=event.data; }; }else{ document.getElementById("result").innerHTML="sorry,your browser does not support web workers"; } } function endWorker(){ w.terminate();//利用Worker對象的terminated方法,終止 w=undefined; } </script> <p>在后臺運行的web worker js文件,webworker.js 才能實現(xiàn)效果<br> var i = 0; <br> function timeCount(){ <br> i = i + 1; <br> postMessage(i);//postMessage是Worker對象的方法,用于向html頁面回傳一段消息 <br> setTimeout("timeCount()",500);//定時任務 <br> } <br> timeCount();//加1計數(shù),每500毫秒調用一次</p> </body> </html>
submitReset Code