setInterval and setTimeout

2019-08-15 04:14发布

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

The first interval is 21 seconds, of the first instance.

the 2nd interval is 3 7-second instances (what I want).

I'm trying to clear all of the above when I click .play.

Any help?

1条回答
你好瞎i
2楼-- · 2019-08-15 04:52

clearTimeout needs to be passed a timeout ID, this ID is returned by setTimeout.

clearTimeout(); does nothing. You can push the return values from setTimeout into an array, and then loop through them, and run 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);
});
查看更多
登录 后发表回答