我正在尝试制作一个从小时而不是几天倒计时的JavaScript时钟。我使用了一个很好的countdown JS script from Stackoverflow,我正在尝试根据自己的喜好调整代码。
我的代码:
// CLOCK
var end = new Date(2017,4,22,23,59);
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;
function clock() {
var now = new Date();
var distance = end - now;
var days = Math.floor(distance / _day);
// get the total day number example, 3 days
// times that by 3, so 3x24 = 72 hours
var plus = days * 24;
// no make the hours + the days, so 4 hours + 72 etc
var hours = Math.floor((distance % _day) / _hour + plus);
var minutes = Math.floor((distance % _hour) / _minute);
var seconds = Math.floor((distance % _minute) / _second);
console.log('Quick! Get the sale while it lasts')
console.log(+hours + ' hours remaining..');
console.log(+seconds + ' seconds remaining..');
console.log(+minutes + ' mins remaining..');
}
var countdownTimer = setInterval('clock()', 1000);
如果今天是5月18日,而结束日期是20日,那么倒计时应该是48小时左右,但它不能正常工作。似乎是使用了旧的2天和15小时..我不想与天有任何关系。我想要几小时而不是几天。
任何指针?
答案 0 :(得分:2)
删除任何依赖于天数(变量,计算)的内容:
var end = new Date('5/22/2017 11:59 PM');
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
function clock(){
var now = new Date();
var distance = end - now;
var hours = Math.floor(distance / _hour);
var minutes = Math.floor((distance % _hour) / _minute);
var seconds = Math.floor((distance % _minute) / _second);
console.log('Quick! Get the sale while it lasts')
console.log(hours + ' hours remaining..');
console.log(minutes + ' mins remaining..');
console.log(seconds + ' seconds remaining..');
}
var countdownTimer = setInterval(clock, 1000);
注意:将字符串作为第一个参数传递给setInterval
被认为是不好的做法;只需传递函数参考。
你会注意到,一旦进入,计数器可能会跳一秒或两次显示相同的秒数,因为setInterval
不能保证呼叫完全分开由给定的延迟。您可以通过计算下一秒何时到期来抵消这种影响,并将该动态延迟提供给setTimeout
。这里还有一些代码可以在目标时刻到来时停止重复:
// CLOCK
var end = new Date('5/22/2017 11:59 PM');
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
function clock(){
var now = new Date();
var distance = end - now;
if (distance <= 0) {
console.log('Sorry, sale has ended.')
return; // stop repeating
}
// More precise delay, so you get a tick every second:
setTimeout(clock, _second*1.5 - now % _second);
var hours = Math.floor(distance / _hour);
var minutes = Math.floor((distance % _hour) / _minute);
var seconds = Math.floor((distance % _minute) / _second);
console.log(hours +':' + ('0' + minutes).substr(-2)
+ ':' + ('0' + seconds).substr(-2) + ' remaining...');
}
clock(); // Just call it
答案 1 :(得分:0)
您可以简单地创建一个函数:
function timestamp() {
let time = new Date();
document.getElementById('').innerHTML = time.toLocaleTimeString();
}
setInterval(timestamp, 1000);
在您的getElementById()中,您的ID名称