首页 > 解决方案 > 如何使用 javascript 制作 HH:MM:SS 倒数计时器?

问题描述

我尝试制作简单的倒数计时器,但我不知道如何在计时器结束时制作某些东西,也不知道如何制作带有小时数的计时器HH。我只能做分钟MM和秒SS

所以,我有这个HTML代码:

<div class="tadc-time-display">
    <span class="tadc-time-display-hours_minutes">00:00</span>
    <span class="tadc-time-display-seconds">00</span>
</div>

JS我以前的代码没用(如果需要,可以使用Native JavaScriptor jQuery

function startTimer(duration, display) {
    var start = Date.now(),
        diff,
        minutes,
        seconds;
    function timer() {
        // get the number of seconds that have elapsed since 
        // startTimer() was called
        diff = duration - (((Date.now() - start) / 1000) | 0);

        // does the same job as parseInt truncates the float
        minutes = (diff / 60) | 0;
        seconds = (diff % 60) | 0;

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds; 

        if (diff <= 0) {
            // add one second so that the count down starts at the full duration
            // example 05:00 not 04:59
            start = Date.now() + 1000;
        }
    };
    // we don't want to wait a full second before the timer starts
    timer();
    setInterval(timer, 1000);
}

window.onload = function () {
    var fiveMinutes = 60 * 0.1,
        display = document.querySelector('#time');
    startTimer(fiveMinutes, display);
};

它也应该startstop并且reset,但我不知道该怎么做(

非常感谢!

标签: javascriptjquery

解决方案


var hours = 0, // obtain these values somewhere else 
  minutes = 1,
  seconds = 20,
  target = new Date(),
  timerDiv = document.getElementById("timer"),
  handler;

function init() { 
 // set the target date time with the counter values
 // counters more then 24h should have a date setup or it wont work
  target.setHours(hours);
  target.setMinutes(minutes);
  target.setSeconds(seconds);
  target.setMilliseconds(0); // make sure that miliseconds is 0
  timerDiv.innerHTML = target.toTimeString().split(" ")[0]; // print the value
}

function updateTimer() {
  var time = target.getTime();
  target.setTime(time - 1000); // subtract 1 second with every thick
  timerDiv.innerHTML = target.toTimeString().split(" ")[0];
  if (
    target.getHours() === 0 &&
    target.getMinutes() === 0 &&
    target.getSeconds() === 0
  ) { // counter should stop
    clearInterval(handler);
  }
}

handler = setInterval(updateTimer, 1000);

document.getElementById("stop-button").addEventListener("click", function() {
  clearInterval(handler);
});
document.getElementById("start-button").addEventListener("click", function() {
  clearInterval(handler);
  handler = setInterval(updateTimer, 1000);
});
document.getElementById("reset-button").addEventListener("click", function() {
  init();
  clearInterval(handler);
});
init();
<div id="timer"></div>
<div>
  <button id="start-button">Start</button>
  <button id="stop-button">Stop</button>
  <button id="reset-button">Reset</button>
</div>

这是带有评论的工作示例。


推荐阅读