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.jsjavascript

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);
}
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息