I’m currently developing a countdown timer using JavaScript, and I’ve encountered an issue where the timer automatically restarts after reaching 00:00:00. My initial implementation attempts to reset the timer display to its original state upon reaching zero, but this inadvertently causes the timer to restart.
var seconds;
var temp;
var GivenTime = document.getElementById('countdown').innerHTML;
function countdown() {
time = document.getElementById('countdown').innerHTML;
timeArray = time.split(':')
seconds = timeToSeconds(timeArray);
if (seconds == '') {
temp = document.getElementById('countdown');
temp.innerHTML = GivenTime;
time = document.getElementById('countdown').innerHTML;
timeArray = time.split(':')
seconds = timeToSeconds(timeArray);
}
seconds--;
temp = document.getElementById('countdown');
temp.innerHTML= secondsToTime(seconds);
timeoutMyOswego = setTimeout(countdown, 1000);
}
function timeToSeconds(timeArray) {
var minutes = (timeArray[0] * 1);
var seconds = (minutes * 60) + (timeArray[1] * 1);
return seconds;
}
function secondsToTime(secs) {
var hours = Math.floor(secs / (60 * 60));
hours = hours < 10? '0' + hours : hours;
var divisor_for_minutes = secs % (60 * 60);
var minutes = Math.floor(divisor_for_minutes / 60);
minutes = minutes < 10? '0' + minutes : minutes;
var divisor_for_seconds = divisor_for_minutes % 60;
var seconds = Math.ceil(divisor_for_seconds);
seconds = seconds < 10? '0' + seconds : seconds;
return minutes + ':' + seconds;
}
countdown();
However, this approach doesn’t effectively solve the problem because the timer continues to run even after reaching 00:00:00. I’ve attempted to address this by checking if seconds is equal to an empty string (”) and resetting the timer display to GivenTime, but this seems to trigger the countdown again instead of stopping it.
Could anyone suggest a way to modify my code so that the countdown timer stops completely at 00:00:00 without restarting?