setInterval and setTimeout


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 时,我正在尝试清除上述所有内容。

有什么帮助吗?

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

最新更新