javascript watching for variable change via a timer
Posted
by DA
on Stack Overflow
See other posts from Stack Overflow
or by DA
Published on 2010-04-26T22:15:31Z
Indexed on
2010/04/26
22:23 UTC
Read the original article
Hit count: 218
I have a slide show where every 10 seconds the next image loads. Once an image loads, it waits 10 seconds (setTimeout) and then calls a function which fades it out, then calls the function again to fade in the next image. It repeats indefinitely.
This works.
However, at times, I'm going to want to over-ride this "function1 call -> pause -> function2 call -> function1 call" loop outside of this function (for instance, I may click on a slide # and want to jump directly to that slide and cancel the current pause).
One solution seems to be to set up a variable, allow other events to change that variable and then in my original function chain, check for any changes before continuing the loop.
I have this set up:
var ping = 500;
var pausetime = 10000;
for(i=0; i<=pausetime; i=i+ping){
setTimeout(function(){
console.log(gocheckthevariable());
console.log(i);
pseudoIf('the variable is true AND the timer is done then...do the next thing')
},i)
}
The idea is that I'd like to pause for 10 seconds. During this pause, every half second I'll check to see if this should be stopped.
The above will write out to the console the following every half second:
true
10000
true
10000
true
10000
etc...
But what I want/need is this:
true
0
true
500
true
1000
etc...
The basic problem is that the for loop executes before each of the set timeouts. While I can check the value of the variable every half second, I can't match that against the current loop index.
I'm sure this is a common issue, but I'm at a loss what I should actually be searching for.
© Stack Overflow or respective owner