plh97 / blog

✏️blog. writing in issues.
https://plhh.xyz/
82 stars 8 forks source link

Worker 前端如何多线程计算复杂数据 #149

Open plh97 opened 5 years ago

plh97 commented 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>

js

onmessage = function (e) {
  let res = 0;
  for (let i = 0; i < e.data; i++) {
    res+=i
  }
  var workerResult = res;
  postMessage(workerResult);
}

前端时刻更新着时间, 分支线程计算数据,互不影响

image

计算完成,将结果抛出

image