我有一些代码可以从特定日期开始计数。我如何才能做到这一点,所以当我单击网页上的按钮时,它会重置为0,然后继续计数吗?
我有以下js代码:
const second = 1000,
minute = second * 60,
hour = minute * 60,
day = hour * 24;
let countUp = new Date('February 07, 2019 16:24:00').getTime(),
x = setInterval(function() {
let now = new Date().getTime(),
distance = now - countUp;
document.getElementById('days').innerText = Math.floor(distance / (day)),
document.getElementById('hours').innerText = Math.floor((distance % (day)) / (hour)),
document.getElementById('minutes').innerText = Math.floor((distance % (hour)) / (minute)),
document.getElementById('seconds').innerText = Math.floor((distance % (minute)) / (second));
}, second)
提前谢谢!
答案 0 :(得分:0)
您需要存储间隔的计时器句柄,并在单击按钮时将其取消。将您的计时器代码转换为创建间隔检查器的函数:
function createNewTimer(date){
return setInterval(function() {
let now = date,
distance = now - countUp;
document.getElementById('days').innerText = Math.floor(distance / (day)),
document.getElementById('hours').innerText = Math.floor((distance % (day)) / (hour)),
document.getElementById('minutes').innerText = Math.floor((distance % (hour)) / (minute)),
document.getElementById('seconds').innerText = Math.floor((distance % (minute)) / (second));
}, second);
}
var timerId = createNewTimer(new Date('February 07, 2019 16:24:00').getTime());
var element = // select your element
element.addEventListener('click', function() {
clearInterval(timerId);
timerId = createNewTimer(new Date().getTime())
}, false);
这说明了如何重置计时器并为时间的开始日期增加可变性的基本思想