Reputation: 13
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/
Upvotes: 1
Views: 441
Reputation: 207557
You got a bug
setTimeout(autoPlay(), delay); <-- you are calling the function right away.
You need to drop the ()
setTimeout(autoPlay, delay);
Upvotes: 0
Reputation: 23208
you should pass reference of function instead of function returned value
use setTimeout(autoPlay, delay); instead of setTimeout(autoPlay(), delay);
you should clearInterval inside autoPlay so that it clear older setInterval if called again and again.
var myInterval ;
function autoPlay() {
clearInterval(myInterval); // clear older setInterval.
myInterval = setInterval(function() {
..............
Upvotes: 1
Reputation: 1407
use a global variable to store the id of the setTimeout:
var timer = 0;
$('#sliderNav a').click(function(e) {
timer = setTimeout(autoPlay(), delay);
});
...
// Stop autoPlay() on hover
$('#slider, #sliderNav a').hover(function() {
clearInterval(timer);
},
....
Upvotes: 0