Search code examples
javascripttimercountdown

Add 0's to this countdown timer


I finally managed to make my 24 hour non-date dependable countdown timer. The purpose of this is that the countdown starts every time someone visits the site. The problem is that when any unit (hours, mins, secs) reaches single digits values display them as such instead of the standard time format (9 minutes instead of 09 minutes, as it should). How can I implement a condition that if a value it's <= 9 it adds a 0 before it?

var count = 86400;
var counter = setInterval(timer, 1000); //1000 will  run it every 1 second

function timer() {
  count = count - 1;
  if (count == -1) {
    clearInterval(counter);
    return;
  }

  var seconds = count % 60;
  var minutes = Math.floor(count / 60);
  var hours = Math.floor(minutes / 60);
  minutes %= 60;
  hours %= 60;

  document.getElementById("timer").innerHTML = hours + ":" + minutes + ":" + seconds; // watch for spelling
}
 <span id='timer'></span>


Solution

  • Create one function similar to following that does the job for you:

    function makeMeTwoDigits(n){
        return (n < 10 ? "0" : "") + n;
    }
    

    And before printing your numbers call this function:

    document.getElementById("timer").innerHTML = makeMeTwoDigits(hours) + ":" + makeMeTwoDigits(minutes) + ":" + makeMeTwoDigits(seconds);
    

    Explanation:

    Like @rfornal said, we're checking if the number is less that 10 which means single digit, add '0' and return otherwise add nothing and return.

    One point to observe is this won't work if the number is negative.