I’ve written a simple Slider in jQuery with autplay. If autoplay is enabled a setTimeout is set that points to a function. This function then has a recursive setTimeout to itself.
All works well, except in Chrome. After I’ve changed a tab, wait for a while and return, the slider is freaking out. It looks like there are multiple instances of the timeout active… but that cannot be the case since I appoint the timeout to the same variable.
Some relevant code:
var timer;
function autoplay() {
currentPosition++;
if(currentPosition == numberOfSlides) {
// last slide
currentPosition = 0;
}
manageNavigation(currentPosition);
// Hide / show controls
manageControls(currentPosition);
// animate the slides
slideshowAnimate();
// set timer
if(autoplay_enable) {
//clearTimeout(timer);
timer = setTimeout(function() { autoplay() }, interval*1000)
}
}
function setTimer() {
if(autoplay_enable) {
timer = setTimeout(function() { autoplay() }, interval*1000)
}
}
setTimer();
No, resetting the value of
timerwill not cancel the current timer. For that you need toclearTimeout. All timer holds is a numeric reference to the timer, not a closure or anything of that nature.Assuming you have a good condition to start
setTimer(), your code should look more like this: