gpt4 book ai didi

Javascript Countdown Timer Repeat 和 Count total 重复次数

转载 作者:行者123 更新时间:2023-11-29 17:56:37 25 4
gpt4 key购买 nike

我有 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 Countdown Timer Repeat 和 Count total 重复次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38537805/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com