Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery reset setInterval timer

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

I want the timer to be reset when clicked on #reset.

like image 499
Rails beginner Avatar asked Aug 02 '12 15:08

Rails beginner


1 Answers

or you could do something along these lines:

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

and run when you need to:

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

like image 152
GnrlBzik Avatar answered Oct 04 '22 09:10

GnrlBzik