[英]A simple countdown timer displaying Hours, Minutes, Seconds
I am trying to create a countdown timer, struggling to make it show hours, then minutes, then seconds. 我正在尝试创建一个倒数计时器,努力使它显示小时,然后是分钟,然后是秒。
function startTimer(duration, display) {
var start = Date.now(),
diff,
hours,
minutes,
seconds;
function timer() {
// get the number of seconds that have elapsed since
// startTimer() was called
diff = duration - (((Date.now() - start) / 1000) | 0);
// Setting and displaying hours, minutes, seconds
hours = (diff / 360) | 0;
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = hours + ":" + minutes + ":" + seconds;
if (diff <= 0) {
// add one second so that the count down starts at the full duration
// example 17:00:00 not 16:59:59
start = Date.now() + 1000;
}
};
// don't want to wait a full second before the timer starts
timer();
setInterval(timer, 1000);
}
window.onload = function () {
var timeLeft = 3600 * 17,
display = document.querySelector('#time');
startTimer(timeLeft, display);
};
Struggling to get minutes and hours displaying correctly. 努力使分钟和小时正确显示。
As well as this I need the timer to start at midnight and countdown for 17 hours. 除此之外,我还需要计时器从午夜开始计时,倒数17小时。 Thinking along the lines of 3600 * 17 (17 hours) then take off the duration left?
按照3600 * 17(17小时)的思路思考,然后减去剩余时间吗?
var timeLeft = ((3600 * 17) - diff),
You have a typo and 2 minor computation flaws: 您有错别字和2个较小的计算缺陷:
function timer: 功能定时器:
hours = (diff / 3600) | 0; // was: hours = (diff / 360) | 0;
minutes = ((diff % 3600) / 60) | 0;
onload-Handler: onload-Handler:
var hoursMinutesSeconds = 3600 * 17, // was: 360 * 60 * 17; alternative: 60 * 60 * 17
display = document.querySelector('#time');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.