我正在为应用程序设置一个倒数计时器,当该倒数达到00:00的标记时,我希望在重新开始倒数之前有5秒的延迟。我该如何使用setTimeout()做到这一点?
while true:
run foo.py
答案 0 :(得分:1)
您只需将行timer = duration;
包装在函数中,然后将其传递给setTimeout
。仅在timer >= 0
时显示更新的时间,否则它将显示-ive数字。
const display = document.querySelector('#display')
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
if(timer >= 0){
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
}
if (--timer < 0) {
setTimeout(()=>timer = duration,5000)
}
}, 1000);
duration = timer;
}
startTimer(10,display)
<div id="display"></div>
答案 1 :(得分:0)
欢迎使用Stackoverflow。您可以通过在代码中添加第二个计时器来实现您的目标,如下所示:
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
setTimeout(function(){
timer = duration;
},5000); // 5 seconds delay
}
}, 1000);
duration = timer;
}
答案 2 :(得分:0)
时间间隔将继续滴答,直到您清除它为止,因此,您需要做的是在计时器为零时清除时间间隔,然后设置超时时间以重新启动时间间隔。 (为了清除间隔,您需要先将其返回的句柄存储在变量中。)递归可以在这里有所帮助:
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
var timerInterval = setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
window.clearInterval(timerInterval);
window.setTimeout(() => startTimer(duration, display), 5000);
}
}, 1000);
}
答案 3 :(得分:0)
这是使用setTimeout
的解决方案,不,因为这不是必需的。它只是倒数到-5(不更新显示),然后重新开始。
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
if (timer >= 0) {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
}
--timer;
if (timer <= -5) {
timer = duration;
}
}, 1000);
}
window.onload = function() {
startTimer(10, document.getElementById('display'));
};
<span id="display"></span>