Shoaulin
Shoaulin

Reputation: 127

Javascript Timing

I am trying to create a countdown using javascript. I got some code from here and modified it slighly.

<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 call a countdown repeatedly until the user clicks on a link. It should countdown from 10 by 1 every second (10,9,8,7,6...0) until the link is clicked but it doesn't. Can anybody help me?

EDIT: Does anyone know how to make the countdown restart once it hits 0?

Thank you in advance.

Upvotes: 1

Views: 1045

Answers (1)

geocar
geocar

Reputation: 9305

<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 the counter started. Note my startCount and stopCount don't create multiple interval timers.

Also, the element with id=txt needs to be an <input> or <textarea> box for your code to work. If it's a span, you should use document.getElementById('txt').innerHTML=c;

Finally, you might want timedCount() to stopCount() if c goes below zero. This is easy enough:

if (c <= 0) stopCount();

Upvotes: 6

Related Questions