views:

205

answers:

1

I'm not that great at Javascript, for the record! I DO know how to use ajax. I just need a bit of help.

I'm having a hard time figuring out how to display a 5 minute countdown, and once the countdown hits zero, to run a function. I need to pass a variable to the function that needs to run. I tried SetInterval but this isn't exactly my strong suit. Does anyone have any suggestions? I can post the code I've got, but I would equate it to a gorilla fumbling in the dark at a typewriter!

+2  A: 

Perhaps try it this way. Use setTimeout() to control the "timer" side of the requirement, or differently put, to control the count down on the screen.

When launching the setTimeout(), also launch the function call using setInterval(). setInterval can be used to launch functions after a certain amount of time, and will attempt to run it at those intervals. Once you have run your function though, just use a call to clearInterval() to stop the timer.

Below is some code adapted from a site, it's untested, but should get the idea across.

Countdown Timer: - From here, just modified a bit.

<form name="counter"><input type="text" size="8" 
name="d2"></form> 

<script> 
<!-- 
// 
 var interval="";
 var milisec=0;
 var seconds=300; 
 document.counter.d2.value='500';

function display(){ 
 if (milisec<=0){ 
    milisec=9;
    seconds-=1;
 } 
 if (seconds<=-1){ 
    milisec=0;
    seconds+=1; 
 } 
 else 
    milisec-=1;
    document.counter.d2.value=seconds+"."+milisec;
    setTimeout("display()",100);
    var interval = setInterval("goFunction(\" + seconds + \")", seconds);
} 
display();

goFunction(param)
{
   clearInterval(interval);
   // ... Do what needs doing
}
--> 
</script> 
Kyle Rozendo