I have this simple program that takes a time from the future and creates a countdown until that time:
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = Number(String(timerOrigin.innerHTML)+"000") - now;
// Time calculations for days, hours, minutes and seconds
//Days are not displayed, only used to help calculate hours
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)) + (days * 24);
if (hours.length == 1) {
hours= "0" + hours;
}
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
if (minutes.length == 1) {
minutes= "0" + minutes;
}
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
if (seconds.length == 1) {
seconds = "0" + seconds;
}
// Display the time
timer.innerHTML = hours + ":" + minutes + ":" + seconds;
// If the count down is finished, Display score
if (distance < 0) {
clearInterval(x);
timer.innerHTML = homeTeamScore.innerHTML + "-" + awayTeamScore.innerHTML;
}
}, 1000);
//Push to Dom
sideScore.appendChild(timer)
The issue I'm having is that the single-digit if statements are not working.
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)) + (days * 24);
if (hours.length == 1) {
hours= "0" + hours;
}
this will return 4:22:22 whereas the desired result is 04:22:22. I know I'm missing something somewhere but I cannot put my finger on it. I also ran some log tests and the program is not even getting into the if statements. The console returns no errors as well. Perhaps it's an issue with the scoping since this is all inside of a loop? Any help is appreciated.