首页 > 解决方案 > 如何在javascript中使0 0 0 0后的倒计时时间再次倒计时?

问题描述

我只想知道如何在 0 0 0 0 之后倒计时直接回到 23:59:59 所以当我尝试创建倒计时函数时我遇到了一个问题,当它过期时它会变成 -0d -0h -0m -1s , -0d -0h -0m -2s 但是当我将其刷新回 23.59.58 , 23,59,57 时。我只想知道在明确的时间间隔之后它会直接转到 23.59.59 而不是 -0d -0h -0m -0s 。这是我的脚本

倒计时.js

function warTime2(countDownDate) {
  var countDownDate = new Date();
  countDownDate.setHours(14);
  countDownDate.setMinutes(0);
  countDownDate.setSeconds(0);

  var now = new Date();

  if (now.getHours() < countDownDate.getHours()) {
    countDownDate = countDownDate;
  } else if (countDownDate.getHours() <= now.getHours()) {
    countDownDate.setDate(countDownDate.getDate() + 1);
  }

  var x = setInterval(function () {
    var now = new Date();

    var distance = countDownDate - now;

    // Time calculations for days, hours, minutes and seconds
    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);

    if (hours < 10) {
      hours = "0" + hours;
    }
    if (minutes < 10) {
      minutes = "0" + minutes;
    }
    if (seconds < 10) {
      seconds = "0" + seconds;
    }

    document.getElementById("second_chip_war").innerHTML =
      "02:00 PM War Start in " + hours + ":" + minutes + ":" + seconds;

    if (distance < 0) {
      clearInterval(x);
      let newDate = countDownDate + 8 * 3600 * 1000;
      warTime2(newDate);
    }
  }, 1000);
}

谢谢,很高兴听到你想帮助我

标签: javascriptphp

解决方案


首次分配时需要检查是否distance小于 0,如果是,则countDownDate在重新计算距离并继续函数之前增加一天:

function warTime2(countDownDate) {
  var countDownDate = new Date();
  countDownDate.setHours(14);
  countDownDate.setMinutes(0);
  countDownDate.setSeconds(0);

  var now = new Date();
  if (now.getHours() < countDownDate.getHours()) {
    countDownDate = countDownDate;
  } else
  if (countDownDate.getHours() <= now.getHours()) {
    countDownDate.setDate(countDownDate.getDate() + 1);
  }

  var x = setInterval(function() {
    var now = new Date();

    var distance = countDownDate - now;
    if (distance < 0) {
      // countdown complete, add a day to countDownDate and restart
      countDownDate.setDate(countDownDate.getDate() + 1);
      distance = countDownDate - now;
    }
    // Time calculations for days, hours, minutes and seconds
    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);

    if (hours < 10) {
      hours = "0" + hours;
    }
    if (minutes < 10) {
      minutes = "0" + minutes;
    }
    if (seconds < 10) {
      seconds = "0" + seconds;
    }

    document.getElementById("second_chip_war").innerHTML = "02:00 PM War Start in " + hours + ":" +
      minutes + ":" + seconds;
  }, 1000);
}

warTime2('2020-06-21');
<div id="second_chip_war"></div>


推荐阅读