您好,我想在秒数达到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 :(得分:1)
只需检查剩余的秒数,如果秒数不为0,则继续操作,否则停止:
function Decrement() {
...
if (secs !== 0) {
secs--;
setTimeout('Decrement()',1000);
} else
console.log('Timer stopped');
}
这是一个工作的小提琴:
// 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"/>