2 回答
TA贡献1773条经验 获得超3个赞
你必须告诉它停止。例如,如果时间到了就返回。就像是
if(min <= 0 && sec == 0) {return alert("Time is up!")}
// ^ now the next statements won't run
document.getElementById('time').innerHTML = min + ":" + sec;
setTimeout(startTimer, 1000);
TA贡献1827条经验 获得超7个赞
clearTimeout
计时器完成 5 分钟后,您需要删除计时器。
如果 stackoverflow 片段不起作用,请检查此 - https://jsfiddle.net/e5v80xmk/
document.getElementById('time').innerHTML = 05 + ":" + 00;
document.getElementById('start').addEventListener('click', startTimer);
var timerRef = null;
function startTimer() {
var p_time = document.getElementById('time').innerHTML;
var timeArray = p_time.split(/[:]+/);
var min = timeArray[0];
var sec = checkSecond((timeArray[1] - 1));
if (sec == 59) {
min = min - 1
}
document.getElementById('time').innerHTML = min + ":" + sec;
if (min <= 0 && sec == 0) {
clearTimeout(timerRef)
alert("Time is up!")
return
}
timerRef = setTimeout(startTimer, 1000);
}
function checkSecond(seconds) {
if (seconds < 10 && seconds >= 0) {
seconds = "0" + seconds
};
if (seconds < 0) {
seconds = "59"
};
return seconds;
}
<p>Click the button to begin the quiz. Good Luck!</p>
<button id="start" class="button">Start</button>
<div class="timer">
Timer: <span id="time"> 5:00 </span> minutes
</div>
- 2 回答
- 0 关注
- 107 浏览
添加回答
举报