clearInterval在点击时不会清除(但在悬停时工作正常)

时间:2012-10-08 19:45:33

标签: javascript jquery clearinterval

我做了一个滑块,它自动播放正常,暂停时悬停并在模糊时再次启动。大。

但是当你点击它时,它会启动一个新的间隔并快速进入x2而我无法清除它?

这是我的代码:

// 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();
});

实际工作演示,以便您可以看到实时:http://www.jonheslop.com/canoe/

3 个答案:

答案 0 :(得分:1)

你应该传递函数的引用而不是函数返回值

use setTimeout(autoPlay, delay); instead of  setTimeout(autoPlay(), delay);

你应该在autoPlay中使用clearInterval,以便在反复调用时清除旧的setInterval。

 var myInterval ;
    function autoPlay() {
         clearInterval(myInterval); // clear older setInterval.
        myInterval = setInterval(function() { 
             ..............

答案 1 :(得分:0)

使用全局变量来存储setTimeout的id:

var timer = 0;

$('#sliderNav a').click(function(e) {
    timer  = setTimeout(autoPlay(), delay);
});

...

// Stop autoPlay() on hover
$('#slider, #sliderNav a').hover(function() { 
    clearInterval(timer);   
},

...

答案 2 :(得分:0)

你有一个错误

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

您需要删除()

setTimeout(autoPlay, delay);