简单的小时倒计时

Simple Hour Countdown

我正在尝试做这种倒计时:

现在是 09:20,我想知道 1 小时还剩多少分秒。所以到 10:00.

需要 40 分钟

这个倒计时必须在一天之内连续计算这个差距。

我尝试了以下方法,但没有用:

var now = new Date();
var mins = now.getMinutes();
var secs = now.getSeconds();

function initClock(id) {
  const counter = document.getElementById(id);

  const minutesItem = counter.querySelector('.js-countdown-minutes');
  const secondsItem = counter.querySelector('.js-countdown-seconds');

  function updateClock() {
    mins = now.getMinutes();
    secs = now.getSeconds();

    minutesItem.innerHTML = (60 - mins);
    secondsItem.innerHTML = (secs);

  }

  updateClock();
  const timeinterval = setInterval(updateClock, 1000);
}

initClock('js-countdown');

秒数未更新。

看看这个倒计时,你可以使用这个函数来获得计数器结果。

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

  // Find the distance between now an the count down date
  var distance = initDate - 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);

  // Display the result in the element with id="demo"
  return days + "d " + hours + "h "
  + minutes + "m " + seconds + "s "
}
// Set the date we're counting down to

var countDownDate = new Date("Jan 5, 2018 15:37:25").getTime();
var strCounDown = getCountDown(countDownDate)

document.getElementById("demo").innerHTML = strCounDown;
<p id="demo"></p>

您需要重新贴标 now = new Date();。 它不会在每次 updateClock() 迭代时得到更新。

代码已修复:

function initClock(id, endtime) {
  const counter = document.getElementById(id);

  const minutesItem = counter.querySelector('.js-countdown-minutes');
  const secondsItem = counter.querySelector('.js-countdown-seconds');

  function updateClock() {
    var now = new Date(),
        mins = now.getMinutes(),
        secs = now.getSeconds();

    minutesItem.innerHTML = (60 - mins);
    secondsItem.innerHTML = (secs);

  }

  updateClock();
  const timeinterval = setInterval(updateClock, 1000);
}

initClock('js-countdown', 3600);

顺便说一句,前三行:

var now = new Date();
var mins = now.getMinutes();
var secs = now.getSeconds();

不需要。

老实说,您想要实现的目标没有得到很好的描述。但是如果你想让你的计数器不断更新,你必须在每次调用 updateClock 函数时更新 now 变量。所以,你需要输入:

var now = new Date();
var mins = now.getMinutes();
var secs = now.getSeconds();

在您的 updateClock 函数中。因此,您不需要在代码开头使用这些行。除此之外,我不明白为什么你对 initClock 函数有 endtime 参数,因为你从不使用它。

顺便说一句,如果你说的是倒计时,也许你想将 secondsItem.innerHTML = (secs); 更改为 secondsItem.innerHTML = (60 - secs);