setInteval vs setTimeout



作为这个问题的后续:Hover开始一个简单的幻灯片

如果使用setIntegal函数,Firefox的行为会很奇怪:

这是JSFiddle和脚本:

$('.fadein img:gt(0)').hide();
$(".fadein").hover(function() {
    timer = setInterval(function() {
        $('.fadein :first-child').fadeOut()
            .next('img').fadeIn()
            .end().appendTo('.fadein');
    }, 1000);
}, function() {
    clearInterval(timer);
});

这在Chrome中的功能很好,但当我在Firefox中打开小提琴并在图像上悬停一段时间时,事件开始冒泡,并且不会在鼠标离开时停止。

编辑:

有趣的是,我更改了一些参数,它在Firefox中有效,但在Chrome中无效。我用setTimeout更改了setInterval函数。参见JSFiddle:

$('.fadein img:gt(0)').hide();
$('.fadein').mouseenter(function(){
    timer = setTimeout(function(){
        $('.fadein :first-child').fadeOut().next('img').fadeIn()
        .end().appendTo('.fadein');
    }, 1000);
}) .mouseleave(function() {
    clearTimeout(timer);
});

所以底线是——它仍然没有发挥应有的作用。

在设置计时器之前,您可能想看看计时器是否存在。

$(".fadein").hover(function(){
    if (timer) { clearInterval(timer); }
    timer = setInterval(function(){  

最新更新