If you want to do it per-page, you're almost there. Right now, your code does not allow you to track milliseconds, as your setInterval
runs every second. What I would recommend instead is something like this:
(function() {
var counter = 0,
cDisplay = document.getElementById("counter");
format = function(t) {
var minutes = Math.floor(t/600),
seconds = Math.floor( (t/10) % 60);
minutes = (minutes < 10) ? "0" + minutes.toString() : minutes.toString();
seconds = (seconds < 10) ? "0" + seconds.toString() : seconds.toString();
cDisplay.innerHTML = minutes + ":" + seconds + "." + Math.floor(t % 10);
};
setInterval(function() {
counter++;
format(counter);
},100);
})();
This does a couple of things to allow your code to run 10 times per second:
- The output element,
#counter
, is cached and not retrieved every iteration
- The formatting is kept to arithmetic operations only - modulo and division.
This now also adds leading zeroes.
If you would like to keep this counter running page-per-page, consider using document.cookies
to pass the final value from page to page.
Fiddle
This serves as a good first version. However, you may want to:
- Pause/re-start your timer
- Reset your timer
- Have multiple timers
For this reason, I will add a slightly more complex form of the above code, which will allow you to manage multiple timers. This will make use of a few OO concepts. We will use a TimerManager
object to "host" our timers, and each Timer
object will have a link to the manager.
The reason for this is because every timer will depend on the same setInterval()
by doing it this way, rather than to have multiple setInterval()
calls. This allows you to cut down on wasted clock cycles.
More on this in about 5 minutes!