Question

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/

Was it helpful?

Solution

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() { 
             ..............

OTHER TIPS

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);   
},

....

You got a bug

setTimeout(autoPlay(), delay);  <-- you are calling the function right away.

You need to drop the ()

setTimeout(autoPlay, delay);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top