Search code examples
javascripttitaniumtitanium-alloy

do while loop not working properly in Titanium


I think this should be an easy one but I am at my wits end.

I have created an app that cycles images through the screen in Titanium based on a delay "setInterval".

It cycles the images indefinitely but I would like to add in a function where the user can exit out of the cycle either on a time delay (a set number of iterations through the loop) or just when they push a button ("stop").

This code works to call a function that pulls an image off of my mamp server and creates a new window in Titanium where it is displayed:

setInterval(function(){call();}, 3000);

But when I try to take it a step further it doesn't work.

var keepGoing;
do {
setInterval(function(){call();}, 3000);
}
while (keepGoing);

function stop(e){
return keepGoing = false;
}

The function "stop" is called from my xml like so:

<Button id="stop" onClick="stop">stop</Button>

I've even tried just the following to no avail:

do {
setInterval(function(){call();}, 3000);
}
while (0 > 1);

So that it will cycle once and then stop working.

Any thoughts would be greatly appreciated!


Solution

  • Once you have started setInterval it will go in an infinite loop. If you want to stop the setInterval just call the clearInterval.

    var interval;
    
    interval = setInterval(function(){call();}, 3000);
    
    function stop(e){
        clearInterval(interval);
    }
    

    This has done the work in my case.