HTML5 worker计数器简单示例

效果图:

 

 

index.html

var w;
// 开始
function startWorker() {
    if (typeof (Worker) !== "undefined") {
        if (typeof (w) == "undefined") {
            w = new Worker("a.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() {
    w.terminate();
}

a.js

let num = 0;
setInterval(function () {
    num++;
    postMessage(num);
}, 1000)

 

posted @ 2018-07-09 08:56  最好的年纪  阅读(284)  评论(0编辑  收藏  举报