简体   繁体   中英

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!

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.

You need pattern like that:

function loop () {
    call();   
    if (keepGoing) {
        setTimeout(loop, 3000);
    }
}
loop();

BTW, why the following code won't work is a popular question on interviews (I was asked that several times).

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

The trick is, function passed into setInterval here will be called sometimes after 3s, but only if main thread will be free. And it never will be free - it's doing infinite loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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