Javascript Timing

I am trying to create a countdown using javascript. I got the code here and modified it a bit.

<script type="text/javascript">
var c=10, t;

function timedCount() {
  document.getElementById('txt').value=c;
  c=c-1;
  t=setInterval("timedCount()",1000);
}

function stopCount() {
  clearInterval(t);
}
</script>

      

I need to trigger a countdown until the user clicks on a link. It should count down from 10 to 1 every second (10,9,8,7,6 ... 0) until the link is clicked, but it doesn't. Can anyone help me?

EDIT: Does anyone know how to make a countdown as soon as it reaches 0?

Thanks in advance.

+1


source to share


1 answer


<script type="text/javascript">
var c=10;
var t;
function timedCount()
{
    document.getElementById('txt').value=c;
    c=c-1;
}
function startCount()
{
    if (!t) t=setInterval("timedCount()",1000);
}
function stopCount()
{
    clearInterval(t);
    t=null;
}
</script>

      

Call startCount()

in onload (or whatever) when you want to start the counter. Please note that my startCount and stopCount do not create multiple interval timers.

Also, the element with id = txt must be <input>

or <textarea>

for your code to work. If it is a range you should usedocument.getElementById('txt').innerHTML=c;



Finally, you might want timedCount () to stopCount () if c goes below zero. It's simple enough:

if (c <= 0) stopCount();

      

+6


source







All Articles