HTML5 web worker

1.简介

  web worker 是运行在后台的 JavaScript,独立于其他脚本,不会影响页面的性能。Internet Explorer不支持web worker。

2.worker.js文件

var i=0;
function count(){
    i=i+1;
    postMessage(i);//它用于向 HTML 页面传回一段消息
    setTimeout("count()",500);
}
count();

3.html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="result">显示</div>
    <button onclick="start()">开始</button>
    <button onclick="stop()">结束</button>
    <script>
        var w;
        function start(){
            if(typeof(w)=="undefined"){
                w=new Worker("worker.js");//创建web worker 对象
            }
            //添加事件监听器,当 web worker 传递消息时,会执行下列语句
            w.onmessage=function(event){
                document.getElementById("result").innerHTML=event.data;
            }
        }
        function stop(){
            w.terminate();//终止
        }
        
    </script>
</body>
</html>
由于无法解释的神圣旨意,我们徒然地到处找你;你就是孤独,你就是神秘,比恒河或者日落还要遥远。。。。。。
原文地址:https://www.cnblogs.com/momoli/p/13524809.html