为什么我的周期性倒计时错误地重新启动?

Why is my recurring countdown restarting incorrectly?

我对 Javascript 有点陌生。去年我的倒计时工作正常。然而,圣诞节一到,它就开始倒计时到新年的 2 月 27 日,我不明白为什么。

我尝试移动一些变量(year 和 countDownDate),我还尝试在重新启动 year 时重新启动 countDownDate。但由于这一年还没有重新开始,老实说,我不太确定这些是否有效。

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);

我希望每年圣诞节都能倒计时。那么当圣诞节来临时,就需要开始下一年的倒计时。

我使用了 Tyler Roper 和 iagowp 的以下建议使其正常工作!显示天数的百分之一非常重要。

你这里有一个错误:

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

当天数大于 100 时,您将删除其中一个字符,因此如果天数 = 349,它将变为 49 天。 如果你想确保它至少有两位数,你可以将它替换为

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