Welcome to a tutorial on how to create a simple Javascript stopwatch. So you need to create a simple stopwatch function for your project, your school assignment, or maybe just out of pure curiosity? Well, it is actually pretty easy. Let us walk through the exact steps in this guide – Read on!
TABLE OF CONTENTS
JAVASCRIPT STOPWATCH
All right, let us now get into more details on how the Javascript stopwatch works.
STOPWATCH DEMO
PART 1) STOPWATCH HTML
<div id="stopwatch">
<!-- CURRENT TIME -->
<div id="sw-time">00:00:00</div>
<!-- CONTROLS -->
<input type="button" value="Reset" id="sw-rst" disabled>
<input type="button" value="Start" id="sw-go" disabled>
</div>
This should be very easy to understand. The entire stopwatch is placed inside a <div id="stopwatch">
wrapper, and it only has 3 components –
sw-time
– The time display.sw-rst
– The reset button.sw-go
– The start/stop button.
Just take note that the buttons are disabled. We will only enable them when the page is fully loaded.
PART 2) THE JAVASCRIPT
2A) STOPWATCH PROPERTIES
var sw = {
// (A) PROPERTIES
etime : null, // html time display
erst : null, // html reset button
ego : null, // html start/stop button
timer : null, // timer object
now : 0, // current elapsed time
};
First, Captain Obvious to the rescue – All the stopwatch mechanics are contained within the var sw
object. Here, we start by defining a couple of properties (variables) to hold the common HTML elements, and also the timer itself.
2B) STOPWATCH INITIALIZE
// (B) INITIALIZE
init : () => {
// (B1) GET HTML ELEMENTS
sw.etime = document.getElementById("sw-time");
sw.erst = document.getElementById("sw-rst");
sw.ego = document.getElementById("sw-go");
// (B2) ENABLE BUTTON CONTROLS
sw.erst.onclick = sw.reset;
sw.ego.onclick = sw.start;
sw.erst.disabled = false;
sw.ego.disabled = false;
},
window.addEventListener("load", sw.init);
On page load, sw.init()
will run. All this does is fetch the HTML elements, and “enable” them by attaching the respective start/reset onclick
events.
2C) START & STOP TIMER
// (C) START!
start : () => {
sw.timer = setInterval(sw.tick, 1000);
sw.ego.value = "Stop";
sw.ego.onclick = sw.stop;
},
// (D) STOP
stop : () => {
clearInterval(sw.timer);
sw.timer = null;
sw.ego.value = "Start";
sw.ego.onclick = sw.start;
},
Take note of how this works –
- To start the stopwatch, we set a timer at
sw.timer
to runsw.tick()
at every 1 second. - Once started, we switch the “start” button into a “stop” button.
- To stop, we simply clear the
sw.timer
timer. - Once stopped, we switch the “stop” button back into a “start” button.
2D) TIMER TICKER
// (E) TIMER ACTION
tick : () => {
// (E1) CALCULATE HOURS, MINS, SECONDS
sw.now++;
let hours = 0, mins = 0, secs = 0,
remain = sw.now;
hours = Math.floor(remain / 3600);
remain -= hours * 3600;
mins = Math.floor(remain / 60);
remain -= mins * 60;
secs = remain;
// (E2) UPDATE THE DISPLAY TIMER
if (hours<10) { hours = "0" + hours; }
if (mins<10) { mins = "0" + mins; }
if (secs<10) { secs = "0" + secs; }
sw.etime.innerHTML = hours + ":" + mins + ":" + secs;
},
This one runs at every 1-second interval when the stopwatch is started. Looks confusing at first, but keep calm and look carefully again. All it does is to calculate the elapsed time, and display it in a “nice HOUR:MIN:SEC
manner”.
2E) RESET
// (F) RESET
reset : () => {
if (sw.timer != null) { sw.stop(); }
sw.now = -1;
sw.tick();
}
Stop the current timer and reset the elapsed time back to 0. The end.
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
SORRY FOR THE ADS...
But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.
Buy Me A Coffee Code Boxx eBooks
EXAMPLE CODE DOWNLOAD
Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
EXTRA BITS & LINKS
That’s all for the code, and here is a small extra that may be useful.
MICROSECONDS COUNTER
Need to go down into the microseconds? Of course, it is possible with a couple of changes:
- Update
start()
, set the timer to run in microseconds instead –setInterval(sw.tick, 100)
. - Update
tick()
, this is a little tricky. Remember that the timer is now in microseconds?sw.now++
will literally count in microseconds now. That is:- When
sw.now == 10
, that is 1 second. - When
sw.now == 600
, that is 1 minute. - Lastly,
sw.now == 36000
is 1 hour.
- When
- With that in mind, update the microseconds, seconds, minutes, hours calculation.
- Also, update the HTML display.
COMPATIBILITY CHECKS
- Arrow Function – CanIUse
- Set Interval – CanIUse
Works on all modern browsers. If you switch the arrow function () => {}
back to function () {}
, this stopwatch will run even in the ancient ones.
LINKS & REFERENCES
- Countdown Timer – Code Boxx
- Example on CodePen – JS Stopwatch
THE END
Thank you for reading, and we have come to the end of this guide. I hope that it has helped you to create your own stopwatch project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
Wooooooooow thats saved my life!!!! Awesome job!!!
W.S. Toh take a bow! outstanding job. Best explanation and code for a stopewatch that I have found. Looks pretty. code is sweet. But your step by step explanations are fantastic! thank you for sharing.
bye
eric