Reputation: 105
hello i want to stop my decrement function when second reach 0 see code bellow the problem is when second reach 0 the countdown function still work
<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>
I want to stop this counter when it reaches to 0, can anyone help me?
Upvotes: 0
Views: 670
Reputation: 468
Just check remaining seconds, if they are not 0 you go on, otherwise you stop:
function Decrement() {
...
if (secs !== 0) {
secs--;
setTimeout('Decrement()',1000);
} else
console.log('Timer stopped');
}
Here is a working 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"/>
Upvotes: 1