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

avatarplhDigital nomad

先祭上代码

<!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