I’ve made a slider, it autoplays fine, pauses on hover and starts again on blur. Great.
But when you click, it starts a new interval and goes x2 as fast and I cant get it to clear?
Here is my code:
// Reset autoPlay() if a user clicks a nav button
$('#sliderNav a').click(function(e) {
setTimeout(autoPlay(), delay);
});
// Auto play the slider
var delay = 4000; // 4 seconds
function autoPlay() {
myInterval = setInterval(function() {
currentOffset += itemWidths[clickCount] // Add the current slides width to total offset
$sliderWrap.animate({right: currentOffset}, 500, function() {
clickCount++;
// If this is the last slide when clicking .next, slide to clone then snap back to beginning.
if ( itemWidths.length == clickCount ) {
clickCount = 0;
currentOffset = totalWidth;
$sliderWrap.css('right',currentOffset); // Where we started originally
}
});
}, delay );
}
autoPlay();
// Stop autoPlay() on hover
$('#slider, #sliderNav a').hover(function() {
clearInterval(myInterval);
},
// start autoPlay() on blur
function() {
autoPlay();
});
Actual working demo so you can see it for reals: http://www.jonheslop.com/canoe/
you should pass reference of function instead of function returned value
you should clearInterval inside autoPlay so that it clear older setInterval if called again and again.