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

 

posted @ 2015-04-26 14:09  Mr.Leo  阅读(428)  评论(0编辑  收藏  举报