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 and this guide will walk you through the exact steps – This Javascript timer should take less time to create, than baking a piece of cake. Read on to find out!

ⓘ 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 CSS
The Javascript Useful Bits & Links The End

 

DOWNLOAD & NOTES

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

 

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.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer 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.

 

 

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 the <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, and will only be enabled when the page is fully loaded.

 

 

THE CSS

Next, we add some cosmetic styles to make the interface look nicer.

 

STOPWATCH CSS COSMETICS

stopwatch.css
/* (A) CONTAINER */
#stopwatch {
  display: flex;
  flex-wrap: wrap;
  max-width: 320px;
  margin: 0 auto;
}
 
/* (B) TIME */
#sw-time {
  width: 100%;
  padding: 20px 0;
  font-size: 48px;
  font-weight: bold;
  text-align: center;
  background: #000;
  color: #fff;
}
 
/* (C) BUTTONS */
#sw-rst, #sw-go {
  box-sizing: border-box;
  width: 50%;
  cursor: pointer;
  padding: 20px 0;
  border: 0;
  color: #fff;
  font-size: 20px;
}
#sw-rst { background-color: #a32208; }
#sw-go { background-color: #20a308; }

Well, these are just some simple CSS cosmetics. No hidden tricks nor hacks. Feel free to change this to fit the theme of your own project.

 

 

THE JAVASCRIPT

Finally, we deal with the Javascript that will do most of the heavy weight lifting.

 

STOPWATCH JAVASCRIPT

stopwatch.js
var sw = {
  // (A) INITIALIZE
  etime : null, // HTML time display
  erst : null, // HTML reset button
  ego : null, // HTML start/stop button
  init : function () {
    // (A1) GET HTML ELEMENTS
    sw.etime = document.getElementById("sw-time");
    sw.erst = document.getElementById("sw-rst");
    sw.ego = document.getElementById("sw-go");

    // (A2) ENABLE BUTTON CONTROLS
    sw.erst.addEventListener("click", sw.reset);
    sw.erst.disabled = false;
    sw.ego.addEventListener("click", sw.start);
    sw.ego.disabled = false;
  },

  // (B) TIMER ACTION
  timer : null, // timer object
  now : 0, // current elapsed time
  tick : function () {
    // (B1) CALCULATE HOURS, MINS, SECONDS
    sw.now++;
    var remain = sw.now;
    var hours = Math.floor(remain / 3600);
    remain -= hours * 3600;
    var mins = Math.floor(remain / 60);
    remain -= mins * 60;
    var secs = remain;

    // (B2) 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;
  },
  
  // (C) START!
  start : function () {
    sw.timer = setInterval(sw.tick, 1000);
    sw.ego.value = "Stop";
    sw.ego.removeEventListener("click", sw.start);
    sw.ego.addEventListener("click", sw.stop);
  },

  // (D) STOP
  stop  : function () {
    clearInterval(sw.timer);
    sw.timer = null;
    sw.ego.value = "Start";
    sw.ego.removeEventListener("click", sw.stop);
    sw.ego.addEventListener("click", sw.start);
  },

  // (E) RESET
  reset : function () {
    if (sw.timer != null) { sw.stop(); }
    sw.now = -1;
    sw.tick();
  }
};
window.addEventListener("load", sw.init);

 

 

THE EXPLANATION

So just how does this script work? Well, we will not walk through line-by-line here (trace through the code on your own), but here is a summary of what happens:

  • The var sw object holds all the key players for the stopwatch.
  • When the window is fully loaded, sw.init() will fire up. It basically just gets a reference to the related HTML elements and enables the reset/start buttons.
  • When the user clicks on the start button, sw.start() will fire up, simply creating a timer into sw.timer.
  • At every 1 second interval, sw.tick() will increment the elapsed time and update the timer display.
  • Lastly, sw.stop() and sw.reset() are used to stop the timer.

 

THE SUMMARY

Functions
Function Description
init() Fired on window load, grabs the HTML elements, and enables the stopwatch buttons.
tick() Fired at every 1-second interval, after the stopwatch is started. Calculates the elapsed time, updates the display timer.
start() Starts the stopwatch.
stop() Stops the stopwatch.
reset() Reset and stop the stopwatch.
Properties
Property Description
etime Holds the HTML time display.
erst Holds the HTML reset button.
ego Holds the HTML start/stop button.
timer Holds the timer object.
now Holds the current elapsed time.

 

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 function start(), set the timer to run in microseconds instead – setInterval(sw.tick, 100).
  • Update function 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.

 

COUNTDOWN TIMER

Need a countdown timer instead? Check out my other guide:

3 Steps Simple Javascript Countdown Timer

 

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. Required fields are marked *