且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当条件变量(全局变量)在javascript中更改时,停止循环

更新时间:2023-01-27 15:58:30

JavaScript本质上是单线程的.一旦代码块开始运行,它将在其他任何事情发生之前运行完成.IE,直到将while循环结束后,您将 stop 设置为 true 的事件才会执行.

JavaScript is inherently single threaded. Once a block of code has started running, it will run to completion before anything else happens. IE the event where you're setting stop to true will not execute until after the while loop has finished.

您需要将循环分成多个部分,然后分别运行每个部分,以允许发生其他事件:

You need to split your loop into sections and run each section individually, allowing other events to take place:

stop = false;
var i = 0;

function loopLogic() {
  var tempStop = i + 500;
  while (i < tempStop) {
    //original processing logic
    console.log("hi-" + i);
    i++;
  }

  if (!stop && i < 100000)
    window.setTimeout(loopLogic, 0);

}
window.setTimeout(loopLogic, 0);

这一次将功能分成500个多个块.持续时间为0的 setTimeout 使函数立即(几乎)继续运行,但会将下一个块放在执行链的底部.这允许发生其他事件,因此可以将 stop 更新为 true

This breaks up the function into multiple chunks of 500 at a time. The setTimeout of 0 duration lets the function continue (almost) immediately, but will put the next chunk at the bottom of the execution chain. This allows other events to happen and therefore will allow updating of stop to true

这里是一个小提琴,展示了这种方法.

兼容的浏览器中可用的另一种方法是 Web Worker ,但这已经超出范围了这个问题的范围.

The other approach available in compliant browsers is the Web Worker, but that's starting to get beyond the scope of this question.