Pause and resume setInterval

前端 未结 3 1304
隐瞒了意图╮
隐瞒了意图╮ 2020-12-04 20:13
window.setInterval(function(){
  //do stuff
}, milisec);

Is there a way to stop this interval at will, and to resume it from where it lasted? Say,

3条回答
  •  粉色の甜心
    2020-12-04 20:26

    You should only need setTimeout with a go and stop - http://jsfiddle.net/devitate/QjdUR/1/

    var cnt = 0;
    var fivecnt = 0;
    var go = false;
    
    function timer() {
        if(!go)
            return;
        cnt++;
        if(cnt >= 5){
            cnt=0;
            everyFive();
        }
        jQuery("#counter").text(cnt);
        setTimeout(timer, 1000);
    }
    
    function everyFive(){
        fivecnt++;
        jQuery("#fiver").text(fivecnt);
    }
    
    function stopTimer(){
        go = false;  
    } 
    function startTimer(){
        go = true;
        timer();
    }    
    

提交回复
热议问题