【问题标题】:Attempting to pause setinterval for 10 seconds when button is clicked单击按钮时尝试将 setinterval 暂停 10 秒
【发布时间】:2013-11-01 11:55:56
【问题描述】:

我试图在单击“下一步”按钮时暂时暂停setInterval。目前它会停止当前的 setinterval,但 10 秒后不会再次启动。

我有一个简单的图像旋转器,它每 4 秒改变一次图像。单击“下一步”按钮时,我希望它暂停 10 秒的间隔,然后再次开始 4 秒的旋转。

这是目前的代码(已简化):

var ic = $('#imageContainer');
var numItems = $('.image').size();
var position = 0;
ic.css('left', '0px');

var inter;

function rotate() {
    inter = setInterval(function () {
        if (position == (numItems - 1)) {
            console.log(position);
            $('.image').first().insertAfter($('.image').last());
            ic.css('left', '+=400px');
            position--;
        }
        ic.animate({
            left: "-=400px"
        });
        position += 1;
    }, 4000);
}
rotate();

$('#next').click(function () {
    clearInterval(inter);
    nextInter = setInterval(function () {
        rotate();
    }, 10000);
    clearInterval(nextInter);
});

【问题讨论】:

  • 只是出于好奇,为什么要混合 animateinsert
  • 像这样的问题是一个很好的例子,说明为什么自动射击 setTimeout 通常比 setInterval 更好。

标签: javascript jquery setinterval clearinterval


【解决方案1】:

发生这种情况是因为您在创建 nextInter 后仅清除了一行。

nextInter = setInterval(function(){rotate();}, 10000 );
clearInterval(nextInter);

但是,如果您删除最后一个 clearInterval,您的 nextInter 间隔将每 10 秒调用一次 rotate,这将为每 4 秒设置一个新间隔。这肯定会导致意外的行为。我认为您正在寻找 setTimeout

$('#next').click(function () {
    clearInterval(inter);
    setTimeout(rotate, 10000);
});

此外,如果您想防止多次单击下一个按钮时执行多个 rotates,您可以在回调范围之外创建一个变量来存储您的 setTimeout 实例,然后在按钮出现时将其清除点击。示例:

var rotateTimeout;
$('#next').click(function () {
    clearInterval(inter);
    clearTimeout(rotateTimeout);
    rotateTimeout = setTimeout(rotate, 10000);
});

【讨论】:

【解决方案2】:

在调度nextInter 之后,您将在它执行后不久将其清除。

你需要的是setTimeout(),而不是setInterval()。您需要在 10 秒后调用旋转,但 setInterval 会每 10 秒调用一次,因此您正在清除它,但问题是您在它有机会执行旋转一次之前就将其清除了。

$('#next').click(function () {
    clearInterval(inter);
    setTimeout(rotate, 10000 );
});

【讨论】:

    【解决方案3】:

    您可以使用setTimeout

    $('#next').click(function () {
        clearInterval(inter);
        nextInter = setTimeout(rotate, 10000);
    });
    

    【讨论】:

      猜你喜欢
      • 2016-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多