我有一个从 25 -> 0 的 JavaScript 倒计时器。
var count=25;
var counter=setInterval(timer, 1000); //1000 will run it every 1 second
function timer()
{
count=count-1;
if (count <= 0)
{
clearInterval(counter);
return;
}
document.getElementById("timer").innerHTML=count; // watch for spelling
}
div HTML
<span id="timer">25</span>
现在我希望倒计时在等待 5 秒后自动重复,然后从 25 -> 0 重新开始。我想计算倒计时重复的次数。这可能吗?
请帮忙。
最佳答案
您可以尝试将整个代码包装到一个函数(下例中的 countTimers()
)中,该函数每 30 秒运行一次(每个计时器后 5 秒)。然后,设置一个计数器(下例中的timersCount
)来计算将运行的次数。
请参阅下面的示例:
var timersCount = 0, stopped = false, count, counter; // make count, counter global variables so buttons can access them
var timerCounter = setInterval(countTimers, 30000);
countTimers(); // run countTimers once to start
function timer() {
count = count-1;
document.getElementById("timer").innerHTML=count;
if(count <= 0) {
clearInterval(counter);
return;
}
}
function countTimers() {
timersCount++;
// as per request in the comments, you can set a timer counter as well:
document.getElementById("totalcounter").innerHTML = timersCount;
count = 25;
counter = setInterval(timer, 1000);
}
// button code:
document.getElementById("reset").addEventListener("click", function() {
clearInterval(timerCounter);
clearInterval(counter);
count = 25;
document.getElementById("timer").innerHTML=count;
timersCount = 0;
document.getElementById("totalcounter").innerHTML = timersCount;
stopped = true;
});
document.getElementById("stop").addEventListener("click", function() {
if(stopped)
return;
clearInterval(counter);
stopped = true;
});
document.getElementById("start").addEventListener("click", function() {
if(!stopped)
return;
stopped = false;
counter = setInterval(timer, 1000);
setTimeout(function() {
clearInterval(counter);
timerCounter = setInterval(countTimers, 30000);
countTimers();
}, count*1000);
});
Timer: <span id="timer">25</span><br>
Number of times run: <span id="totalcounter">1</span>
<br><br>
<button id="reset">Reset</button>
<button id="stop">Stop</button>
<button id="start">Start (if stopped)</button>
关于Javascript 倒数计时器重复和重复计数总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38537805/