jQuery重置setInterval计时器

Rai*_*ner 8 javascript jquery

我的Jquery:

function myTimer() {
    var sec = 15
    var timer = setInterval(function() { 
    $('#timer').text(sec--);
    if (sec == -1) {
      clearInterval(timer);
      alert('done');
     } 
    }   , 1000);

}

$("#knap").click(function() {
    myTimer();
});

$("#reset").click(function() {
// set timer to 15 sec again.. 
});
Run Code Online (Sandbox Code Playgroud)

我希望在单击#reset时重置计时器.

Mat*_*att 13

您需要将"timer"变量保留在下次调用myTimer函数时可用的作用域中,以便清除现有的间隔并使用新的间隔重置它.尝试:

var timer;
functionn myTimer() {
    var sec = 15
    clearInterval(timer);
    timer = setInterval(function() { 
    $('#timer').text(sec--);
    if (sec == -1) {
      clearInterval(timer);
      alert('done');
     } 
    }   , 1000);

}

$("#knap").click(function() {
    myTimer();
});

$("#reset").click(function() {
   myTimer();
});
Run Code Online (Sandbox Code Playgroud)


Gnr*_*zik 7

或者你可以沿着这些方向做点什么:

var myTimer = function(){
    var that = this,
        time = 15,
        timer;
    that.set = function() {
        console.log('setting up timer');
        timer = setInterval(function(){
            console.log('running time: ' + time);
        },1000);
    }
    that.reset = function(){
        console.log('clearing timer');
        clearInterval(timer);
    }
    return that;
}();
Run Code Online (Sandbox Code Playgroud)

并在需要时运行:

myTimer.set(); myTimer.reset();