HTML5-WebWorker

技术分享


 

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>HTML5-WebWorker</title>
    </head>
    <body>
        
        web worker实时时间:<div id="workerTime"></div>
        <br />
        主线程获取当前时间:<div id="curTime"></div>
        <button onclick="mainthread()">主线程获取时间</button>
    
        <script type="text/javascript">
            /*
             * Web worker的运行原理和两种线程的详细说明 : http://www.ibm.com/developerworks/cn/web/1112_sunch_webworker/
             */
            var interval;
            if (typeof Worker != undefined) {
                var worker = new Worker("js/webworker.js");
                worker.onmessage = function (event)
                {
                    document.getElementById("workerTime").textContent = event.data;
                }
                interval = setInterval(worker.postMessage("1000000"), 1000);
            }
    
            function mainthread() {
                document.getElementById("curTime").textContent = new Date();
            }
            function stop() {
                clearInterval(interval);
           worker.terminate();
            }
            setTimeout(stop, 60000);//60秒之后清理interval
        </script>
        
    </body>
</html>

 

webworker.js

onmessage = function(event) {
    var msg = event.data;
    for (var i = 0; i < msg; i++) {
        if (!!console && i % 500 == 0) {
            console.info(i);
        }
    }
    var d = new Date();
    postMessage(d);
}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。