Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
plh97 opened this issue Apr 27, 2019 · 0 comments
Open

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

plh97 opened this issue Apr 27, 2019 · 0 comments
Assignees
Labels
javaScript 关于js的一些事

Comments

@plh97
Copy link
Owner

plh97 commented Apr 27, 2019

先祭上代码

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

@plh97 plh97 added the javaScript 关于js的一些事 label Apr 27, 2019
@plh97 plh97 self-assigned this Apr 27, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
javaScript 关于js的一些事
Projects
None yet
Development

No branches or pull requests

1 participant