web-worker计数器,根据输入时间统计次数

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 message
self.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);

 

web-worker计数器,根据输入时间统计次数

如图所示:

1.鼠标放在蓝色框上面开始计时;

2.输入框为600,则每隔600毫秒计数器加一,否则,默认1000毫秒;

3.鼠标移除,停止计数;

 

你可能感兴趣的:(worker)