bradley bradley - 4 months ago 12
Javascript Question

timer keeps getting faster everytime i reset it- javascript/jquery

the timer keeps getting faster every time i reset it, im thinking i need to use clearTimeout but am unsure about how to implement it. Heres 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)/60);
seconds = (timeInSeconds - hours*3600 - minutes*60)
$("#timer").html(hours + ":" + minutes + ":" + seconds);
}
timeout();
}, 1000);
}

Answer

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