效果图:
index.html
var w; // 开始 function startWorker() { if (typeof (Worker) !== "undefined") { if (typeof (w) == "undefined") { w = new Worker("a.js"); } w.onmessage = function (event) { document.getElementById("result").innerHTML = event.data; }; } else { document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Workers..."; } } // 结束 function stopWorker() { w.terminate(); }
a.js
let num = 0; setInterval(function () { num++; postMessage(num); }, 1000)