views:

258

answers:

2
+3  A: 
<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();
geocar
I suggest that you replace [ setInterval("timedCount()",1000); ] with [ setInterval(timedCount,1000); ] because there is no need to have that expression evaluated (I also don't like global variables and had written an object instead, but that's another story)
some
I was trying to stay as close to the posted source as possible; Changing too many things at once is often confusing...
geocar
A: 

I tried your code like so:

<html>
<head>
<script type="text/javascript">
var c=10;
var t;
function timedCount()
{
document.getElementById('txt').value=c;
c=c-1;
if (c<=0) c=10;
}
function startCount()
{
if (!t) t=setInterval("timedCount()",1000);
}
function stopCount()
{
clearInterval(t);
t=null;
}
</script>
</head>
<body>
<form>
<input type="button" value="Start count!" onClick="StartCount()">
<input type="text" id="txt">
<input type="button" value="Stop count!" onClick="stopCount()">
</form>
<p>
Click on the "Start count!" button above to start the timer. The input field will count     forever, starting at 0. Click on the  "Stop    count!" button to stop the counting.
</p>
</body>
</html>

I have changed it like JC said but now the timer doesn't start at all. Does anyone know what is wrong?

Shoaulin
I think you want to call startCount() for "Start count!", not timedCount(). Also, the if statement should probably go at the end of the timedCount() function, it won't do much where you currently have it.
J c
If you want the counter to restart at 10 after reaching 0, set c equal to 10 instead of calling StopCount();
J c
onClick="StartCount()" should be onClick="startCount()" (notice the capital s in start)
Marius
Thank you marius :) It worked
Shoaulin