webworker遇到的坑

都说webWorker可以给js带来多线程开发;好吧,我来试试

主要js代码(webworker)

// webWorkers.js

onmessage = function(data){
  let count = 0;
  for(let i = 1; i < data.data; i++) {
    count += i
  }
  postMessage(count)
}

 

// index.html主要代码

btn1.onclick = function(){
      const work = new Worker('./webWorkers.js')
      let s1 = Date.now()
      let num = parseInt(inp.value, 10)
      work.postMessage(num)
      work.onmessage = function(data){
        res.innerHTML = `times: ${Date.now()-s1}ms,result: ${data.data}`
      }
}

结果:4s左右

直接用主线程计算:

btn1.onclick = function(){
      const work = new Worker('./webWorkers.js')
      let s1 = Date.now()
      let num = parseInt(inp.value, 10)
      work.postMessage(num)
      work.onmessage = function(data){
        res.innerHTML = `times: ${Date.now()-s1}ms,result: ${data.data}`
      }
    }

我操,什么情况?webworker的计算能力有这么差吗?

.......完全找不到问题出在哪里啊!?

继续....

onmessage = function(data){
  let num = data.data
  let s = Date.now()
  let count = 0
  for(let i = 0; i < num; i++) {
    count += i
  }
  // 这样就正常了....
  console.log(Date.now() - s)
  postMessage(count)
}

这样就好了,真是B了狗了.....关键是在正常JS下面写这样的判断也是没有问题的呀.算是一个坑吧,好惨啊!!!~~

你可能感兴趣的:(webworker遇到的坑)