希望大家都过得愉快!
我被要求用JavaScript制作一个计时器,我认为使用performance.now
是个好主意,但是当我尝试重置计时器时,计时器停留在它停止而不是变为零的位置。
let time = performance.now();
function initInterval(){
let taken = performance.now() - time;
let current = (time += taken);
setInterval(function () {
// time calculation to make it easy to read, display
// and eventListener to stop, end of the function
}
}
我想通过函数调用来重置计时器,但是在停止间隔之前,它会一直给我相同的数字。
function resetInterval(){
closebutton.addEventListener('click', () => {
staticTimer.innerHTML = "00:00:00"
initInterval()
console.log('beep');
})
}
答案 0 :(得分:0)
无法重置performance.now()
。您可以做的是在计时器启动时保存当前的performance.now()
,然后再减去它。查看您的代码,只需再次设置“ time = performance.now()”,就完成了。
答案 1 :(得分:0)
否,performance.now()
无法重设。返回的值是自time origin
这是使用js类的简单实现。自从页面加载以来,我将时间保存为一个常量,在返回两者之差之前,我先从this.startTime
和this.endTime
中减去了该时间。
class Timer {
constructor() {
this.startTime = undefined;
this.endTime = undefined;
this.constantTimeSincePageLoad = Math.trunc(performance.now());
}
endTimer() {
if (!this.startTime) return 'please start the timer';
this.endTime = Math.trunc(performance.now());
this.constantTimeSincePageLoad = Math.trunc(performance.now());
this.startTime -+ this.constantTimeSincePageLoad;
this.endTime -+ this.constantTimeSincePageLoad;
const result = this.endTime - this.startTime;
this.startTime = undefined;
this.endTime = undefined;
return result;
}
startTimer() {
this.startTime = Math.trunc(performance.now());
}
}
const timer = new Timer();
// activate the timer
timer.startTimer();
// stop the timer - meant to show that the time is reset on each invocation
setTimeout(() => {
console.log(timer.endTimer());
}, 100)