自动倒数计时器 - Javascript

Auto Countdown Timer - Javascript


我正在尝试让我的计时器 在第一个倒计时结束后 new Date() 自动更改为第二个 new Date()
这样做的目的是为了万一我需要更改倒计时的日期,我将不必在 js 文件过期后手动编辑和上传它。但是我还没搞清楚怎么办。

下面是我试过的脚本,输出是 "EXPIRED"。我哪里做错了?感谢您的支持!

<script>
// Set the date we're counting down to
var countDownDate = new Date("Jan 5, 2020 14:00:00").getTime();
var countDownDate2 = new Date("Jan 15, 2020 14:00:00").getTime();

// Update the count down every 1 second
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 = countDownDate - now;
  var distance2 = countDownDate2 - now;
  var a = distance;

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

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

  // Change to another exp.
  if (distance < 0 && distance2 >0) {
   function changeDate() {
   a = distance2; 
   }
  }
  // If the count down is over, write some text 
  else {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }
}, 1000);
</script>

第一个问题是看distance是否小于1,distance2是否大于1。但是当 distance 仍然有效时(在撰写本文时就是这种情况),它会自动进入 else 分支。

因此,要解决此问题,您需要:

// If the count down is over, write some text 
if (distance2 < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
}

编辑:

第二个问题是您在打印后更改变量。因此,您必须转到 a 的定义并将其更改为:

var a = distance;

收件人:

var a;
if (distance < 0 && distance2 >0) {
    a = distance2; 
} else {
    a = distance;
}