简单小时倒计时

时间:2017-11-20 11:23:01

标签: javascript countdown

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

现在是09:20,我想要多少分钟和几秒钟才能完成1小时。所以需要40分钟到10点。

这个倒计时必须在一天内不断计算这个差距。

我已经尝试了以下但是它没有工作:

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

秒数没有更新。

3 个答案:

答案 0 :(得分:1)

您需要重新评估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();

是不需要的。

答案 1 :(得分:0)

看看这个倒计时,您可以使用此功能来获得计数器结果。

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>

答案 2 :(得分:0)

你想要实现的目标并不是很坦诚。但是,如果您希望不断更新计数器,则每次调用now函数时都必须更新updateClock变量。所以,你需要把它放在:

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

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

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

相关问题