Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 324
bradley Avatar asked Jul 14 '26 07:07

bradley


2 Answers

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);
}
like image 200
Louys Patrice Bessette Avatar answered Jul 19 '26 03:07

Louys Patrice Bessette


You should: use setInterval instead of setTimeout, return the interval id that setInterval generates, clear that interval before you restart it. Here is an example: https://jsfiddle.net/8n2b7x0s/

$(function(){
        var sessionmin = 25;
        var intervalId = null;
        $("#sessionMinutes").html(sessionmin);
        $("#circle").click(function() {  
            timeInSeconds = sessionmin * 60;
            // clear the current interval so your code isn't running multiple times
            clearInterval(intervalId);
            // restart the timer
            intervalId = run();
        });
 })

function run(){
    return setInterval(function () {
        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);
        }
    }, 1000);
}
like image 39
Rob M. Avatar answered Jul 19 '26 03:07

Rob M.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!