码迷,mamicode.com
首页 > Web开发 > 详细

HTML5-WebWorker

时间:2015-04-26 15:11:09      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:

技术分享


 

<!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);
}

 

HTML5-WebWorker

标签:

原文地址:http://www.cnblogs.com/blog-leo/p/4457707.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!