我想做一个本地计时器

时间:2018-12-27 16:09:00

标签: javascript timer

我想对1H进行本地倒计时,我想让代码暂停计时器并恢复它! &我在网上搜索,但发现了可用来计算入驻天数的代码

PS:代码是来自w3schools的演示(但它仍在计算即将到来的天数,是的)

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


var x = setInterval(function() {


  var now = new Date().getTime();


  var distance = countDownDate - now;

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


  document.getElementById("demo").innerHTML = days + "d " + hours + "h "
  + minutes + "m " + seconds + "s ";

  if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }
}, 1000);

expected results: code counting 1h
actual results: code counting incoming days

1 个答案:

答案 0 :(得分:0)

您的代码开始,只需进行一些更改即可获得所需的内容:

const ONE_HOUR_ON_MILLIS = 1000 * 60 * 60;
var countDownDate;
var running;
var remainingMillis;
var update;
initCountdown();

function startInterval() {
    return setInterval(function () {
        var now = new Date().getTime();
        remainingMillis = countDownDate - now;

        var hours = Math.floor((remainingMillis % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((remainingMillis % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((remainingMillis % (1000 * 60)) / 1000);
        var millis = Math.floor((remainingMillis % 1000));
        document.getElementById("demo").innerHTML = hours + ":" + minutes + ":" + seconds + "." + millis;

        if (remainingMillis < 0) {
            clearInterval(update);
            document.getElementById("demo").innerHTML = "EXPIRED";
        }
    }, 10);
}

function stop() {
    if (running) {
        var now = new Date().getTime();
        remainingMillis = countDownDate - now;
        running = false;
        clearInterval(update);
    } else {
        alert('cant stop');
    }
}

function start() {
    if (!running) {
        countDownDate = new Date().getTime() + remainingMillis;
        update = startInterval();
        running = true;
    }
}

function initCountdown() {
    countDownDate = new Date().getTime() + ONE_HOUR_ON_MILLIS;
    update = startInterval();
    running = true;
}

function restart() {
    initCountdown();
    debugger;
}
<span id="demo">COUNTDOWN</span>
<div class="controls">
    <button id="start" onclick="start()">Start</button>
    <button id="stop" onclick="stop()">Stop</button>
    <button id="restart" onclick="restart()">Restart</button>
</div>

这应该做您想要的。

相关问题