setInterval and setTimeout

别来无恙 提交于 2020-01-05 10:35:27

问题


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:


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


来源:https://stackoverflow.com/questions/9385555/setinterval-and-settimeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!