使用异步来阻止循环阻止UX

时间:2020-08-24 01:33:26

标签: javascript asynchronous while-loop promise async-await

在某些情况下,我无法控制,我有一个while循环,必须在使用Vanilla JS的应用程序的前端运行。 while循环当前在运行ui约5秒钟时阻止ui,因此它非常明显。我试图使用异步功能无济于事。该功能可以归结为这一点。任何帮助将不胜感激。

let func = () => {
  let num=0;
  while(num<1000000){
   num = Math.random()*1000001
  }
  // do some stuff
}

1 个答案:

答案 0 :(得分:1)

您可以使用Worker API来完成真正的多线程任务:

main.js

const worker = new Worker('worker.js');

worker.onmessage = ({ data }) => {
  // the data is the calculated num
  console.log('result', data);

  // do some stuff
}

// This is where it's actually calling the loop function, and it's non-blocking
worker.postMessage({});

worker.js

onmessage = function () {
  let num=0;
  while(num<1000000){
    num = Math.random()*1000001
  }
  postMessage(num);
}