其他分享
首页 > 其他分享> > 第十八课--H5Web Workers

第十八课--H5Web Workers

作者:互联网

web worker 是运行在后台的 JavaScript,不会影响页面的性能。
html:
w=new Worker("demo_workers.js");
w.onmessage=function(event){
    document.getElementById("result").innerHTML=event.data;
};//onmessage 事件监听器
w.terminate();//终止
w = undefined;//
js:
var i=0;
function timedCount()
{
    i=i+1;
    postMessage(i);//向页面返回数据
    setTimeout("timedCount()",500);
}
timedCount();
看案例
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Web Workers</title>
</head>
<body>
<p>计数: <output id="result"></output></p>
<button οnclick="startWorker()">开始工作</button>
<button οnclick="stopWorker()">停止工作</button>

<p><strong>注意:</strong> Internet Explorer 9 及更早 IE 版本浏览器不支持 Web Workers.</p>

<script>
var w;

function startWorker() {
    if(typeof(Worker) !== "undefined") {
        if(typeof(w) == "undefined") {
            w = new Worker("demo_workers.js");
        }
        w.onmessage = function(event) {
            document.getElementById("result").innerHTML = event.data;
        };
    } else {
        document.getElementById("result").innerHTML = "抱歉,你的浏览器不支持 Web Workers...";
    }
}

function stopWorker()
{
    w.terminate();
    w = undefined;
}
</script>
</body>
</html>

 

标签:function,timedCount,Web,undefined,第十八,Workers,H5Web,event
来源: https://blog.csdn.net/weixin_36691991/article/details/98320519