I have a JavaScript countdown function that is working well, but I am unsure how to stop and refresh the timer to extend the time. When I call the function again before it times out, it behaves strangely by showing two countdown timers because the updateTimer() function is still active. After searching online, I came across the clearTimeout() function as a solution to stop this issue, but I don't know how to implement it in this function.
Can someone please assist me in stopping and refreshing this timer?
function countdown(elementName, minutes, seconds) {
var element, endTime, hours, mins, msLeft, time;
function twoDigits(n) {
return (n <= 9 ? "0" + n : n);
}
function updateTimer() {
msLeft = endTime - (+new Date);
if (msLeft < 1000) {
element.innerHTML = "00:00";
} else {
time = new Date(msLeft);
hours = time.getUTCHours();
mins = time.getUTCMinutes();
element.innerHTML = twoDigits(time.getUTCMinutes()) + ':' + twoDigits(time.getUTCSeconds());
setTimeout(updateTimer, time.getUTCMilliseconds() + 500);
}
}
element = document.getElementById(elementName);
endTime = (+new Date) + 1000 * (60 * minutes + seconds) + 500;
updateTimer();
return stopTimer();
}
countdown("countdown", 0, 30);