1、worker.js
var i = 0; function timeCount(){ i = i + 1; postMessage(i); //postMessage是Worker对象的方法,用于向html页面回传一段消息 setTimeout("timeCount()",500); //定时任务 } timeCount(); //加1计数,每500毫秒调用一次
2、webworkers.html
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Web Worker 测试</title> </head> <body> <h2>Web Worker 测试</h2> <p>计数: <output id="line"></output></p> <button onclick="startWorker()">开始工作</button> <button onclick="stopWorker()">停止工作</button> <p><strong>注意:</strong> Internet Explorer 9 及更早 IE 版本浏览器不支持 Web Workers.</p> <script type="text/javascript"> var wk; function startWorker() { if(typeof(Worker) != "undefined") { if(typeof(wk) == "undefined") { wk = new Worker("worker.js"); } wk.onmessage = function(event) { document.getElementById("line").innerHTML = event.data; }; } else { document.getElementById("line").innerHTML = "抱歉,你的浏览器不支持 Web Workers..."; } } function stopWorker() { wk.terminate(); wk = undefined; } </script> </body> </html>