https://developer.mozilla.org/zh-CN/docs/Web/API/Worker
就是单独去执行一个任务,不影响主线程的任何操作
实现过程
目录结构
主线程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| <!DOCTYPE html> <html lang="zh-cn">
<head> <meta charset="utf-8"> <title>worker</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head>
<body>
<p>工作: <output id="result"></output></p> <button onclick="startWorker()">开始工作</button> <button onclick="stopWorker()">停止工作</button> <hr /> <input type="text"> <script> var W;
function startWorker() { W = new Worker("./worker.js"); console.log(W); W.onmessage = function (event) { console.log(event); document.getElementById("result").innerHTML = event.data; }; }
function stopWorker() { W.terminate(); W = undefined; } </script> </body>
</html>
|
子线程
worker.js
1 2 3 4 5
| var i = 0; setInterval(() => { i = i + 1; postMessage(i); }, 1000);
|
效果展示