简体   繁体   English

如何从JavaScript中的无限运行循环中退出?

[英]How can I exit out from an infinitely runnng loop in JavaScript?

Is it possible to stop an infinite loop from running at all? 是否可以完全停止无限循环?

Right now I am doing something like this: 现在我正在做这样的事情:

var run = true;

loop ({
  if(run) {
  whatever
  }
}, 30),

Then when I want to stop it I change run to false , and to true when I want to start it again. 然后,当我想要停止它时,将run更改为false ,并在再次启动时将其更改为true

But the loop is always running whatever I do. 但是无论我做什么,循环总是在运行。 It just not executing the code inside. 它只是不执行内部代码。

Is there a way to stop it completely? 有没有办法完全阻止它? and make it start again when I want? 并在需要时重新开始?

If I am understanding your question correctly, what you need is the break keyword. 如果我正确理解了您的问题,那么您需要的是break关键字。 Here 's an example. 是一个例子。

SetInterval will give you a loop you can cancel. SetInterval将为您提供一个可以取消的循环。

setInterval ( "doSomething()", 5000 );

function doSomething ( )
{
  // (do something here)
}

Set the interval to a small value and use clearinterval to cancel it 将间隔设置为较小的值,然后使用clearinterval取消设置

function infiniteLoop() {
    run=true;
    while(run==true) {
        //Do stuff
        if(change_happened) {
            run=false;
        }
    }
}
infiniteLoop();

It may not be exactly what you are looking for, but you could try setInterval . 可能不是您要找的东西,但是您可以尝试setInterval

var intervalId = setInterval(myFunc, 0); var intervalId = setInterval(myFunc,0);

function myFun() {
    if(condition) {
        clearInverval(intervalId);
    }
    ...
}

setInterval will also not block the page. setInterval也不会阻止该页面。 You clear the interval as shown with clearInterval . 您可以清除间隔,如clearInterval所示。

Use a while loop 使用while循环

while(run){
    //loop guts
}

When run is false the loop exits. 如果run为false,则循环退出。 Put it in a function and call it when you want to begin the loop again. 将其放在函数中,并在您要再次开始循环时调用它。

The problem is that javascript only has a single thread to run on. 问题是javascript只有一个线程可以运行。 This means that while you are infinitely looping nothing else can happen. 这意味着当您无限循环时,其他任何事情都不会发生。 As a result, it's impossible for your variable to ever change. 因此,您的变量永远都不可能更改。

One solution to this is to use setTimeout to loop with a very small time passed to it. 一种解决方案是使用setTimeout在传递给它的时间很少的情况下进行循环。 For example: 例如:

function doStuff(){
   if(someFlag){
      // do something
   }

   setTimeout(doStuff,1);
}

doStuff();

This will give the possibility for other actions to make use of the thread and potentially change the flag. 这将使其他操作可以利用线程并可能更改标志。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM