Simple Stopwatch With Pure Javascript (Free Source Code)

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!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

TABLE OF CONTENTS

Download & Demo The HTML The Javascript
Useful Bits & Links The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

STOPWATCH DEMO

00:00:00

 

THE HTML

All right, let us start with the foundation of the project, by creating the HTML interface first.

 

STOPWATCH HTML

index.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.

 

 

STOPWATCH JAVASCRIPT

Then, let us deal with the Javascript that does most of the stopwatch heavy weight lifting.

 

A) STOPWATCH PROPERTIES

stopwatch.js
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.

 

B) STOPWATCH INITIALIZE

stopwatch.js
// (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.

 

 

C & D) START & STOP TIMER

stopwatch.js
// (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 run sw.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.

 

E) TIMER TICKER

stopwatch.js
// (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”.

 

 

F) RESET

stopwatch.js
// (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.

 

USEFUL 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.
  • With that in mind, update the microseconds, seconds, minutes, hours calculation.
  • Also, update the HTML display.

 

COMPATIBILITY CHECKS

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

 

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!

2 thoughts on “Simple Stopwatch With Pure Javascript (Free Source Code)”

  1. 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

Leave a Comment

Your email address will not be published.