如何使Web Worker异步?

时间:2018-09-14 13:26:14

标签: javascript asynchronous web-worker worker

任务是:在Worker中处理大量数据,并在每次迭代后呈现算法的结果(我将 dataObj 呈现到HTML)。使用以下代码可使网页冻结和变慢。如何避免呢?

onmessage = (e) => {
	let number = 0;
	let totalNumbers = 0;
	let primeNumbers = 0;

	if (e.data === "start"){
		while(true){
			totalNumbers++;
			if (isPrime(number)){
				primeNumbers++;
			}
			number++;

			let dataObj = {
				totalNumbers: totalNumbers,
				primeNumbers: primeNumbers
			}

			postMessage(dataObj);
		}
	} else{
		
	}
}

function isPrime(n) {
  if (n == 2 || n == 3 || n == 5 || n == 7) {
    return true;
  } else if ((n < 2) || (n % 2 == 0)) {
    return false;
  } else {
    for (var i = 3; i <= Math.sqrt(n); i += 2) {
      if (n % i == 0)
        return false;
    }
    return true;
  }
}

0 个答案:

没有答案