Reputation: 469
I have this function that implements a countdown (MM:SS). I pass the minutes and seconds in the function and the countdown will start. Now, I'd like the countdown to reset and restart everytime I pass new values in. Currently what happens is that if I call the countdown function multiple times then I will have multiple timers running together while instead I need to reset and restart the same timer everytime I pass in new minutes and seconds. Thanks
function countdown(minutes, seconds)
{
var endTime, hours, mins, msLeft, time;
function twoDigits( n )
{
return (n <= 9 ? "0" + n : n);
}
function updateTimer()
{
canvas.style.color = "black";
canvas.innerHTML = "00:00"; //clear canvas
msLeft = endTime - (+new Date);
if ( msLeft < 1000 )
flashyText();
else {
canvas.style.color = "white";
time = new Date( msLeft );
hours = time.getUTCHours();
mins = time.getUTCMinutes();
canvas.innerHTML = (hours ? hours + ':' + twoDigits( mins ) : mins) + ':' + twoDigits( time.getUTCSeconds());
setTimeout( updateTimer, time.getUTCMilliseconds() + 500 );
}
}
endTime = (+new Date) + 1000 * (60*minutes + seconds) + 500;
updateTimer();
}
Upvotes: 0
Views: 1076
Reputation: 1312
Retrieve the id of the current timer and cancel it before setting the new one.
Courtesy w3schools: -
var myVar;
function myFunction() {
myVar = setTimeout(function(){ alert("Hello") }, 3000);
}
function myStopFunction() {
clearTimeout(myVar);
}
Upvotes: 1