[英]How do I stop and reset a setInterval timer
How do I stop and reset this setInterval timer back to 00:00? 如何停止并将setInterval计时器重置为00:00?
Setting clearInterval(timer);
设置
clearInterval(timer);
works for stopping the time but I can't figure out how to reset the time value back to 00:00. 可用于停止时间,但我不知道如何将时间值重置回00:00。
Here's where I'm at: 我在这里:
HTML 的HTML
<span class="timer">
<label id="minutes">00</label>:<label id="seconds">00</label>
</span>
JS JS
const minutesLabel = document.getElementById("minutes");
const secondsLabel = document.getElementById("seconds");
let timer = setInterval(setTime, 1000);
function setTime() {
++totalSeconds;
secondsLabel.innerHTML = pad(totalSeconds % 60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
}
function pad(val) {
let valString = val + "";
if (valString.length < 2) {
return "0" + valString;
} else {
return valString;
}
}
stopTimer = () => {
clearInterval(timer);
timer = setInterval(setTime, 1000);
};
I'm using this timer in a game so based on the users state I need to be able start
, stop
, and restart
the time back to 0. 我在游戏中使用此计时器,因此根据用户状态,我需要能够将
start
, stop
和restart
时间恢复为0。
The variable totalSeconds keeps track of your time. 变量totalSeconds可以跟踪您的时间。 The name of your function stopTimer() - maybe it should be restartTimer - seems a bit misleading since you're restarting the timer there but basically just set totalSeconds to 0 like:
函数stopTimer()的名称-也许应该是restartTimer-似乎有点误导,因为您要在那里重新启动计时器,但基本上只是将totalSeconds设置为0,例如:
stopTimer = () => {
totalSeconds = 0;
clearInterval(timer);
timer = setInterval(setTime, 1000);
};
What's happening now is that your variable keeps going up, even when you "reset" the timer. 现在发生的事情是,即使您“重置”了计时器,您的变量也不断增加。
Simply add 只需添加
totalSeconds = 0;
to your stopTimer
function. 到您的
stopTimer
函数。 This will reset the variable to zero. 这会将变量重置为零。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.