Reputation: 23
I'm sort of a JS newbie here, and working on a countdown timer that begins after a given time period. Basically, a clock starts when the user clicks a button, and a second clock starts when that first timer runs out. I understand that "setInterval" is the best way accomplish this. The main problem I am facing is that the second timer, although it pops up on the screen, does not start counting down. I believe this is because I am trying to run a setInterval within a setInterval, but not sure. Also the lead timer "beeps" at 1 instead of 0. Below is the code. The countdown function begins when a form button is pressed.
<script>
function countdown(form){
lead = form.leadseconds.value;
cd = form.cdseconds.value;
startLeader = setInterval(leadtimer, 1000);
}
function leadtimer(){
if (lead > 0){
document.getElementById("leadtime").innerHTML = lead;
lead--;
}
if (lead == 0){
document.getElementById("leadtime").innerHTML = "beep";
startTimer = setInterval(cdtimer, 1000);
clearInterval(startLeader);
}
}
function cdtimer(){
if (cd > 0){
document.getElementById("cdtime").innerHTML = cd;
lead--;
}
if (cd == 0){
document.getElementById("cdtime").innerHTML = "beepbeep";
clearInterval(startTimer);
}
}
</script>
Any help would be appreciated. Thanks!
Upvotes: 2
Views: 1466
Reputation: 37059
First problem: You're getting the "beep" one second early because when lead
gets to 1
, the first if (lead > 0
) happens as usual, and lead
is decremented. lead
now equals zero. Then execution moves along to the second if. Since you just decremented lead
to zero, that if body gets executed as well. You want an "else if", so only one of the two blocks ever executes. Like so:
if ( lead > 0 ) {
// Do stuff.
lead--;
} else if ( lead == 0 ) {
// Do other stuff.
}
Secondly, in cdtimer()
, you're decrementing lead
: lead--;
. I'd guess that was a mistake that crept in when you copied the first timer function and renamed it. At least, that's how I always end up with code like that.
Also, of course, you want to use the else if
in cdtimer()
as well.
Upvotes: 1