0

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.

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?

2
  • I don't understand your code, could you post the actual one? Is loop a function? Commented Sep 30, 2011 at 20:30
  • @Liso22, what loop you mean ? you can exit for and while with break, setTimeout with flag, setInterval with clearInterval. Commented Sep 30, 2011 at 21:08

6 Answers 6

5

If I am understanding your question correctly, what you need is the break keyword. Here's an example.

Sign up to request clarification or add additional context in comments.

Comments

1

SetInterval will give you a loop you can cancel.

setInterval ( "doSomething()", 5000 );

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

Set the interval to a small value and use clearinterval to cancel it

Comments

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

Comments

0

It may not be exactly what you are looking for, but you could try setInterval.

var intervalId = setInterval(myFunc, 0);

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

setInterval will also not block the page. You clear the interval as shown with clearInterval.

Comments

0

Use a while loop

while(run){
    //loop guts
}

When run is false the loop exits. Put it in a function and call it when you want to begin the loop again.

Comments

0

The problem is that javascript only has a single thread to run on. 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. 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.