【问题标题】:setInterval and setTimeoutsetInterval 和 setTimeout
【发布时间】:2012-02-22 05:48:13
【问题描述】:
var myTimer = setInterval(function(){
    var eleID = '';
    var delayTimer = '';
    $('#hp-fcas li').each(function(i) {
        eleID = $(this).attr('id');
        delayedTrigger( $('#'+eleID + ' a'), 7000*i);
    });
    function delayedTrigger(elem, delay){
        setTimeout(function(){
            $(elem).trigger('click');
        }, delay );
    }
}, 21000);

$(".play").click(function(){
    clearTimeout();
    clearInterval(myTimer);
});

第一个间隔是 21 秒,第一个实例。

第二个间隔是 3 个 7 秒的实例(我想要的)。

当我点击 .play 时,我正在尝试清除以上所有内容。

有什么帮助吗?

【问题讨论】:

  • 您能描述一下您遇到的问题吗?
  • 点击播放时间隔是否清除成功?还是两者都继续?
  • Rocky 修复了第二个问题(清除超时),不敢相信我没有想到这一点。第一个问题是第一个循环是第一次触发的 21 秒

标签: jquery settimeout setinterval


【解决方案1】:

clearTimeout需要传递一个超时ID,这个ID是setTimeout返回的。

clearTimeout(); 什么都不做。您可以将setTimeout 的返回值推入一个数组,然后循环遍历它们,然后运行clearTimeout

var timeouts = []; // Array of timeouts
var myTimer = setInterval(function(){
    var eleID = '';
    var delayTimer = '';
    $('#hp-fcas li').each(function(i) {
        eleID = $(this).attr('id');
        delayedTrigger( $('#'+eleID + ' a'), 7000*i);
    });
    function delayedTrigger(elem, delay){
       timeouts.push(setTimeout(function(){ // push onto array
           $(elem).trigger('click');
       }, delay));
    }
}, 21000);

$(".play").click(function(){
    $.each(timeouts, function(i,v){ // clear all timeouts
       clearTimeout(v);
    });
    clearInterval(myTimer);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-11
    相关资源
    最近更新 更多