Bob said:
Hello,
I am not a js programmer, but i was hoping to find a prewritten script
that i may be able to use. all i need is a simple count up timer that
has a start, pause, and stop control to it, i have found some, but they
all seem to reset once you pause them, and i need it to stay where it
is at and then continue from the paused point once someone hits
restart.
If you want a counter that resonably accurately counts seconds, you
need to use a date object and run the counter every 50ms or so to grab
the system time and use that to count in roughly equal seconds.
If you just want a counter that runs about every 100ms or so and time
accuracy is not important, then the script below will do the job.
<script type="text/javascript">
var pageCounter = (function()
{
var counterLag = 100; // Milliseconds between updates
var counterValue = 0; // Initial value
var counterRef; // Reference to current timer
var textElement; // Element to displaying value
return {
// Initialise values and start the timer if one isn't
// running already. Don't zero the counter
start : function(id)
{
if (!document.getElementById) return;
textElement = document.getElementById(id);
if (!textElement) return;
if (!counterRef) pageCounter.run();
},
// Run the counter - uses setTimeout to call itself
// reasonably regularly and update the counter.
run : function()
{
textElement.innerHTML = counterValue++;
counterRef = setTimeout('pageCounter.run()', counterLag);
},
// Stop the counter but don't zero the counter
stop : function()
{
if (counterRef) clearTimeout(counterRef);
counterRef = null;
},
// Stop and zero the counter
clear : function()
{
if (counterRef) pageCounter.stop();
counterValue = 0;
textElement.innerHTML = counterValue;
}
}
})();
</script>
<button onclick="pageCounter.start('xx')">Start</button>
<button onclick="pageCounter.stop()">Stop</button>
<button onclick="pageCounter.clear()">Clear</button>
<br><span id="xx"></span>