创建一个简单的2分钟倒计时



我想计算2分钟,但到目前为止,我想让你点击"开始"按钮,并设法使其工作,但我在分钟中出现了一个错误,该错误没有运行好,但显示为NaN:秒。

我给他们看我正在处理的代码。

var timeoutHandle;
function countdown(minutes) {
var seconds = 60;
var mins = minutes
function tick() {
var counter = document.getElementById("timer");
var current_minutes = mins-1
seconds--;
counter.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
if( seconds > 0 ) {

timeoutHandle=setTimeout(tick, 1000);

} else {
if(mins > 1){
// countdown(mins-1);   never reach “00″ issue solved:Contributed by Victor Streithorst
setTimeout(function () { countdown(mins - 1); }, 1000);
}
document.getElementById("timer").innerHTML = "Finished"
}
}
tick();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="tempo-completo">
<div id="timer">2:00</div>
<button onclick="countdown()">INICIAR</button>
	</div>

您没有将分钟数传递给countdown()函数。

var timeoutHandle;
function countdown(minutes) {
var seconds = 60;
var mins = minutes
function tick() {
var counter = document.getElementById("timer");
var current_minutes = mins-1
seconds--;
counter.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
if( seconds > 0 ) {

timeoutHandle=setTimeout(tick, 1000);

} else {
if(mins > 1){
// countdown(mins-1);   never reach “00″ issue solved:Contributed by Victor Streithorst
setTimeout(function () { countdown(mins - 1); }, 1000);
}
document.getElementById("timer").innerHTML = "Finished"
}
}
tick();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="tempo-completo">
<div id="timer">2:00</div>
<button onclick="countdown(2)">INICIAR</button>
	</div>

Jeremy Harris的答案很好,但我想提出另一个答案
不要使用setTimeout来生成区间函数,请使用setInterval。将setTimeout与递归循环一起使用总体上不那么精确
考虑到这一点,我在推特上发布了你的代码,以包含这个想法。

var timeoutHandle;
function countdown(minutes) {
var seconds = 60;
var mins = minutes
var counter = document.getElementById("timer");
var current_minutes = mins-1
// we create an interval variable to clear it later
// we also use an arrow function to have access to variable
// outside of the current function's scope.
let interval = setInterval(() => {
seconds--;
counter.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
// our seconds have run out
if(seconds <= 0) {
// our minutes have run out
if(current_minutes <= 0) {
// we display the finished message and clear the interval so it stops.
counter.innerHTML = "Finished"
clearInterval(interval);
} else {
// otherwise, we decrement the number of minutes and change the seconds back to 60.
current_minutes--;
seconds = 60;
}
}
// we set our interval to a second.
}, 1000);
}

<div class="tempo-completo">
<div id="timer">2:00</div>
<button onclick="countdown(2)">INICIAR</button>
	</div>

最新更新