Reputation: 12400
I have a simple function that animates a bunch of images by crossfading them. A simple banner rotation. I set up the function so that calling animateSlideshow("play")
it should set the timeout and start animating and by calling animateSlideshow("stop")
it should stop.
When I call stop, however, the animation happens one more time. What is the cause for this one extra animation and how can I deal with it?
this calls the function on the bottom
function prevSlide(e){
if(curHashIndex !== 0){
$(prevBtn).off();
// Stop the current slideshow
animateSlideshow("stop");
// Reset the current slideshow
$("li.active .rightSlide > li").fadeOut(600).eq(0).fadeIn(600).addClass("actvImg");
$(".rightSlides").animate({
"left" : '+=345'
}, 600, function(){
$(prevBtn).on('click', prevSlide);
});
$(".leftSlides").animate({
"left" : '+=417'
}, 600);
// Activate the new slide
$(".rightSlides li.active").removeClass("active").prev().addClass("active");
activeSlide = $(".rightSlides li.active");
total = $(".rightSlides li.active .rightSlide > li").length;
// Start slideshow on the new slide
var delay = setTimeout(animateSlideshow("play"), 10000);
updateHash();
}
}
function animateSlideshow(action){
if(action === "play"){
$(activeSlide).data('animateSlideshow',
setTimeout(function(){
if( $(actvImg).index() === total - 1 ){
$(actvImg).fadeOut(animationSpeed).removeClass("actvImg").siblings().eq(0).fadeIn(animationSpeed).addClass("actvImg");
}else{
$(actvImg).fadeOut(animationSpeed).removeClass("actvImg").next().fadeIn(animationSpeed).addClass("actvImg");
}
actvImg = $(".rightSlides li.active .rightSlide > li.actvImg");
actvImgIndx = $(actvImg).index();
updateBreadcrumbs();
animateSlideshow("play")
}, animationTimeout)
);
}else{
clearTimeout($(activeSlide).data('animateSlideshow'));
};
};
Upvotes: 0
Views: 512
Reputation: 1577
You should use setInterval() / clearInterval() rather than recalling the function using setTimeout().
function animateSlideshow(action){
if(action === "play"){
$(activeSlide).data('animateSlideshow',
setInterval(function(){
if( $(actvImg).index() === total - 1 ){
$(actvImg).fadeOut(animationSpeed).removeClass("actvImg").siblings().eq(0).fadeIn(animationSpeed).addClass("actvImg");
}else{
$(actvImg).fadeOut(animationSpeed).removeClass("actvImg").next().fadeIn(animationSpeed).addClass("actvImg");
}
actvImg = $(".rightSlides li.active .rightSlide > li.actvImg");
actvImgIndx = $(actvImg).index();
updateBreadcrumbs();
}, animationTimeout);
);
}else{
clearInterval($(activeSlide).data('animateSlideshow'));
};
};
Upvotes: 3
Reputation: 79830
I am not sure why it is failing for you, but I tried a similar demo and it worked for me..
DEMO here
Additionally, I used .stop() to stop the current animation. You can use it if you want to stop the current animation on that object.
Upvotes: 2