Search code examples
javascriptjquerytimersettimeoutcleartimeout

Timer keeps getting faster on every reset


The timer keeps getting faster every time I reset it. I'm thinking I need to use clearTimeout but am unsure about how to implement it. Here's the code:

$(function(){
  sessionmin = 25;
  $("#sessionMinutes").html(sessionmin);
  $("#circle").click(function() {  
    timeInSeconds = sessionmin * 60;
    timeout();
  });
})

function timeout(){
  setTimeout(function () {
    if (timeInSeconds > 0) {
      timeInSeconds -= 1;
      hours = Math.floor(timeInSeconds/3600);
      minutes = Math.floor((timeInSeconds - hours*3600)/60);
      seconds = Math.floor(timeInSeconds - hours*3600 - minutes*60);
      $("#timer").html(hours + ":" + minutes + ":" + seconds);
    }
    timeout();
  }, 1000);
}

Solution

  • You have to define your setTimeout as a variable to reset it.

    See Fiddle

    var thisTimer;      // Variable declaration.
    $(function(){
            sessionmin = 25;
            $("#sessionMinutes").html(sessionmin);
            $("#circle").click(function(){  
                clearTimeout(thisTimer);        // Clear previous timeout
                timeInSeconds = sessionmin * 60;
                timeout();
            });
     })
    
    function timeout(){
        thisTimer = setTimeout(function () {    // define a timeout into a variable
            if(timeInSeconds>0){
            timeInSeconds-=1;
            hours = Math.floor(timeInSeconds/3600);
            minutes = Math.floor((timeInSeconds - hours)/60);
            seconds = (timeInSeconds - hours*3600 - minutes*60)
            $("#timer").html(hours + ":" + minutes + ":" + seconds);
            }
        timeout();
        }, 1000);
    }