Why, the motivation
Doing a search on Google for javascript stopwatch seems to yield no usable object-oriented source code. It's all old school and tied to the HTML that is set-up on the specific page. I found a need for an isolated stopwatch in an Mac OS X widget that I was developing.
Demo
00:00:00
How to use, 3 steps
- Include the library:
<script type="text/javascript" src="stopwatch.js"></script> - Create and start the watch:
var w = new Stopwatch(); w.start();
- Stop it and alert the elapsed time
w.stop(); alert(w.toString());
Download
Documentation
new Stopwatch([listener, resolution])
Creates a Stopwatch object with the specified tick listener function and resolution milliseconds. See setListener() for more info. Both arguments are optional.
Stopwatch.stop()
Stops the watch and returns the elased time as an object. See Stopwatch.getElapsed() for the return format.
Stopwatch.start()
Starts the watch. If a listener is attached via setListener() the listener is triggered each time resolution milliseconds has passed. The resolution can be set via watch.resolution = 1000 (one second) or via the constructor: new Stopwatch(listener, 1000).
Stopwatch.reset()
Resets the watch to 0. If the watch is running it will continue to run from 0.
Stopwatch.restart()
Restarts the watch from 0. Equivalent to calling stop(), reset() and start().
Stopwatch.getElapsed()
Returns the total elapsed time in an object. The attributes are: hours, minutes, seconds and milliseconds. Example:
var e = myWatch.getElapsed(); alert(e.hours + "h "+e.minutes+"m "+e.seconds+"s "+e.milliseconds+"ms has passed");
Stopwatch.setElapsed(hours, minutes, seconds)
Resets the stopwatch and elapsed time to the specific time. It does not stop the watch, so a running watch will immediately continue from the specified time. All parameters are added together. Thus, specifying more than 60 minutes or 60 seconds is allowed and will act as if adding 1 hour or 1 minute respectively. Specifying 1.5 hours is also equivalent to specifying 1 hour and 30 minutes.
Stopwatch.toString()
Returns a human readable version of the elapsed time. Also works while running.
Stopwatch.setListener(listenerFunction)
Sets the listener of the stopwatch. The specified listener function will be called each time Stopwatch.resolution milliseconds has passed. Typically used for updating the display of a watch. Example:
myWatch.setListener(updateClock); function updateClock(watch) { document.getElementById('Time passed: '+watch.toString()); }
Thanks, that was really useful
Great script! At last a timer that doesn't use an input box. Thanks.
I implemented you code in a basic web site with the start, stop and reset functions, but the reset will not go back to "00:00:00:000". It does however begin again from 0 when the start button is pushed. How do I get the reset button to display the correct formatted content?
Thanks.
Pingback: Javascript Stopwatch