iam using this code to animate a slideshow
$(document).ready(function() {
/* slider initiate */
var timer = setInterval(slider,5000);
});
/* slider code */
var position = 0;
function slider() {
$('.slider .thumbs a').removeClass('selected');
position += 660;
var newPosition = position * (-1) + 'px';
if (position == 1980) {
position = 0;
newPosition = '0px';
}
var index = position / 660;
$('.slider .thumbs a').eq(index).addClass('selected');
$('.slider .slider-container').animate({left: newPosition}, 1000);
}
/* click animation */
$('.slider .thumbs a').click(function(){
$('.slider .thumbs a').removeClass('selected');
$(this).addClass('selected');
var index = $(this).index();
var newPosition = index * (-660) +'px';
$('.slider .slider-container').animate({left: newPosition}, 1000);
clearInterval(timer);
var timer = setInterval(slider,5000);
});
but when i click on the thumbs the timer only accelerate that means that clearInterval doesn't work that happens too when i try to clear it on hover
It's a scope problem.
I guess timer is undefined when you try to clear it (try to see with
console.log()
).It accelerate because since you
clearInterval
onundefined
value you clear nothing, and you have 2 interval running at once.Define your first
timer
var outside the$(document).ready
scope.Also, don't re-define
var timer
inside theslider
func. Just re-use the one you declared before.But before all, don't re-use
setInterval
insideslide
. You launch an interval within an other interval. You should usesetTimeout
if you need to set it again.Conclusion
This is enough. With
setTimeout
you don't need to cancel it since it trigger only once. Set another timeout while you need to and it will simulate asetInterval
without the need of canceling it.