簡體   English   中英

我想做一個本地計時器

[英]I want make a local 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

您的代碼開始,只需進行一些更改即可獲得所需內容:

 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>

這應該做你想做的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM