你好,我想在第二个达到 0 时停止我的递减函数,请参阅下面的代码,问题是当第二个达到 0 时,倒计时功能仍然有效
<script type="text/javascript">
// set minutes
var mins = 5;
// calculate the seconds (don't change this! unless time progresses at a different speed for you...)
var secs = mins * 60;
function countdown() {
setTimeout('Decrement()',1000);
}
function Decrement() {
if (document.getElementById) {
minutes = document.getElementById("minutes");
seconds = document.getElementById("seconds");
// if less than a minute remaining
if (seconds < 59) {
seconds.value = secs;
} else {
minutes.value = getminutes();
seconds.value = getseconds();
}
secs--;
setTimeout('Decrement()',1000);
}
}
function getminutes() {
// minutes is seconds divided by 60, rounded down
mins = Math.floor(secs / 60);
return mins;
}
function getseconds() {
// take mins remaining (as seconds) away from total seconds remaining
return secs-Math.round(mins *60);
}
</script>
<script>
countdown();
</script>
我想在计数器达到 0 时停止该计数器,有人可以帮助我吗?
最佳答案
只需检查剩余秒数,如果它们不为 0,则继续,否则停止:
function Decrement() {
...
if (secs !== 0) {
secs--;
setTimeout('Decrement()',1000);
} else
console.log('Timer stopped');
}
这是一个工作 fiddle :
// set minutes
var mins = 1;
// calculate the seconds (don't change this! unless time progresses at a different speed for you...)
var secs = mins * 60;
function countdown() {
setTimeout('Decrement()',1000);
}
function Decrement() {
if (document.getElementById) {
minutes = document.getElementById("minutes");
seconds = document.getElementById("seconds");
// if less than a minute remaining
if (seconds < 59) {
seconds.value = secs;
} else {
minutes.value = getminutes();
seconds.value = getseconds();
}
if (secs !== 0) {
secs--;
setTimeout('Decrement()',1000);
} else
console.log('Timer stopped');
}
}
function getminutes() {
// minutes is seconds divided by 60, rounded down
mins = Math.floor(secs / 60);
return mins;
}
function getseconds() {
// take mins remaining (as seconds) away from total seconds remaining
return secs-Math.round(mins *60);
}
countdown();
<input id="minutes"/> : <input id="seconds"/>
关于javascript - 当达到 0 时停止倒计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53585544/