標籤:des style blog http color io os ar java
1.用web-worker實現:另起一個線程,將計數工作運行在背景JavaScript檔案,並返回累加後的結果。
該js檔案運行於後台,獨立於其他指令碼,不會影響頁面的效能。html頁面可以繼續做任何事情,而此時web worker在後台運行,互不干擾。
在用chrome調試時候出現錯誤:
Uncaught SecurityError: Failed to construct ‘Worker‘: Script at ‘file:///Users/***/Desktop/myworker.js‘ cannot be accessed from origin ‘null‘.
原因在於:“Chrome doesn‘t let you load web workers when running scripts from a local file. Note: Firefox won‘t work either. Try Safari. ”;
附上連結:http://stackoverflow.com/questions/21408510/chrome-cant-load-web-worker
2.根據使用者輸入時間間隔來計數,比如輸入1000,則每隔一秒計數一次;
3.test.html用postmessage向myworkers.js傳訊息,並用onmessage方法收訊息;
myworkers.js用postmessage給test.html發訊息,但是通過self.addEventListener(‘message‘, function(e){});來捕獲message事件,擷取test.html發來的訊息。通常我們用window.addEventListener(‘message‘,function(e){});來添加訊息事件,但是web worker不支援window object(http://stackoverflow.com/questions/11219775/global-variable-in-web-worker),所以只能用self;
test.html頁面如下:
<html><script type="text/javascript"> var myworker; var i = 10; myworker = new Worker("./myworker.js"); myworker.onmessage = function(event){ document.getElementById("result").innerHTML = event.data; } function countStart(){ var value = document.getElementById("textinput").value; myworker.postMessage({"moustevent":1,"textinput":value});//1 start count } function countStop(){ myworker.postMessage({"moustevent":0}); }</script><style type="text/css"> .countTime{ width:100px; height:100px; background-color:blue; }</style><body> <p>Count numbers: <output id="result"></output></p> <div class="countTime" id="countTime" onmouseover="countStart()" onmouseout="countStop()"></div> <p>Please Input Interval Time:</p> <input id="textinput" type="number" ></input></body></html>
注意:
如果想post多個參數,可以考慮post一個json過去;
myworker.js
var i = 1;var pid = 0;var tmp;function countTime(){ i+=1; postMessage(i); };//add event listener to handle the different messageself.addEventListener(‘message‘, function(e){ //if message == 1 start count tmp = e.data["textinput"]; if(1 == e.data["moustevent"]){ if(tmp <= 0) tmp = 1000; pid = setInterval(countTime, tmp); } //if message == 0 stop count else{ clearInterval(pid); }});
注意:
要clearInterval必須有個id指明登出那個interval,所以定義時pid = setInterval(countTime, tmp);
登出時clearInterval(pid);
:
1.滑鼠放在藍色框上面開始計時;
2.輸入框為600,則每隔600毫秒計數器加一,否則,預設1000毫秒;
3.滑鼠移除,停止計數;
web-worker計數器,根據輸入時間統計次數