Search code examples
javascriptcountdown

Why is my recurring countdown restarting incorrectly?


I'm somewhat new to Javascript. Last year my countdown worked correctly. However, as soon Christmas hit, it started counting down to February 27 of the new year and I can't figure out why.

I tried moving some of the variables (year and countDownDate) and I also tried restarting countDownDate when I restart year. But since the year hasn't restarted I'm honestly not too sure if either of these worked.

var d = new Date();
var year = d.getFullYear();
// Set the date we're counting down to
var countDownDate = new Date("Dec 25, " + year + " 0:00:01").getTime();

// Update the count down every 1 second
var x = setInterval(function() {

  // Get todays date and time
  var now = new Date().getTime();

  // Find the distance between now and the count down date
  var distance = countDownDate - now;

  // Time calculations for days, hours, minutes and seconds
  var days = Math.floor(distance / (1000 * 60 * 60 * 24));
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);

  // Output the result in an element with id="demo"
  document.getElementById("demo").innerHTML = ('0' + days).slice(-2) + "d " + ('0' + hours).slice(-2) + "h " + ('0' + minutes).slice(-2) + "m " + ('0' + seconds).slice(-2) + "s ";

  // If the count down is over, restart timer to next Christmas 
  if (distance == 0) {
    year = d.getFullYear() + 1;
  }
}, 1000);

I would like it to countdown to Christmas each year. So then when Christmas hits it needs to begin the countdown for the next year.

I used the advice below from Tyler Roper and iagowp to make it work correctly! Showing the hundredths place for the days is very important.


Solution

  • You have a bug here:

    ('0' + days).slice(-2)
    

    When days are bigger than 100, you are removing one of the chars, so if days = 349, it will become 49 days. If you want to make sure it has at least double digits, you could replace it by

    (days > 10 ? days : '0' + days) + "d " + ('0' + hours).slice(-2) + "h " + ('0' + minutes).slice(-2) + "m " + ('0' + seconds).slice(-2) + "s ";