Open plh97 opened 5 years ago
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div class="time"></div> <script> setInterval(() => { document.querySelector(".time").innerHTML = new Date() }, 1000); var myWorker = new Worker('/testjs/worker.js'); myWorker.postMessage(39999999); // 监听 worker 完成情况 myWorker.onmessage = function (e) { console.log('result from work:', e.data); } </script> </body> </html>
onmessage = function (e) { let res = 0; for (let i = 0; i < e.data; i++) { res+=i } var workerResult = res; postMessage(workerResult); }
先祭上代码
js
前端时刻更新着时间, 分支线程计算数据,互不影响
计算完成,将结果抛出