[英]Javascript - Breaking Infinite Loop?
Is it possible to do something like this, and end a seemingly infinite loop once a condition is met? 是否可以做这样的事情,并在满足条件后结束看似无限的循环? When I attempt it, it crashes my browser as an infinite loop should. 当我尝试它时,它会像无限循环一样使我的浏览器崩溃。 Is there another way to do this or is it not possible? 还有其他方法可以做到吗?
var nL=true;
while(nL){
if(/* Condition */){
nL=true;
break;
}
}
If /* Condition */
is ever true then the loop will end - as break
will end the loop, irrespective of what nL
is set to. 如果/* Condition */
是有史以来真,那么循环将结束-如break
将结束循环,不管什么nL
设置为。
Thus the problem is /* Condition */
is never true. 因此,问题是/* Condition */
永远不会成立。
Now, as Matt Greer pointed out, if the goal really is to loop infinitely (or to loop a really long time), this must be done in either small batches (such as with setTimeout
) or off the current global context (such as with Web Workers) such that browser will not freeze. 现在,正如Matt Greer指出的那样,如果目标实际上是无限循环(或循环很长的时间),则必须以小批量(例如,使用setTimeout
)或在当前全局上下文之外(例如,使用Web Workers),这样浏览器就不会冻结。
var nL=true;
while(nL){
if(/* Condition */){
nL=false; // Set to false to exit loop
break; // Don't need this, if you set nL to false.
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.