JS 2 minute countdown then execute a function?

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!

Answers


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> 

Need Your Help

How to format an Address for multiline display?

android street-address

Similar to this question from 2011, which lacks a satisfactory answer:

C# Open Source Project Namespace

c# .net open-source namespaces

I am considering releasing one of my class libraries written in C# as open source. Before doing that, I am trying to do some refactoring so that it meets the demands of the general public :)