当条件变量(全局变量)在javascript中更改时,停止循环 [英] Stop loop when condition variable (global var) changes in javascript

查看:58
本文介绍了当条件变量(全局变量)在javascript中更改时,停止循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了无法解决的问题.我在javascript中有一个循环,其中要停止的条件变量取决于全局变量.循环开始循环,当我更改该全局变量的值时,它永远不会停止.

I'm having a problem that I can't solve. I have a loop in javascript where the condition variable to stop depends on a global variable. The loop starts looping and when I change the value of that global variable it never stops.

stop = false;
var i = 0;
while ((stop == false) && (i<100000)){
    console.log("hi-"+i);
    i++;
}

当循环正在运行时,如果我停止= true,则它永远不会停止.我不知道为什么.

While loop is running, if I do stop = true, it never stops. I do not know why is that.

有什么主意吗?

谢谢!

推荐答案

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.

这篇关于当条件变量(全局变量)在javascript中更改时,停止循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆