Stopwatch Class (JavaScript)

stopwatch-classIn this challenge we will create an interactive stopwatch using HTML, CSS and JavaScript. The aim of this blog post is to use Object Oriented Programming to create our own Stopwatch class.

Step 1: Stopwatch Class and its constructor

First we will create a class for our stopwatch and use its constructor to initialise all the properties of the class as follows:

  • state: the state of the stopwatch, either “paused” or “running”, initially set to “paused”.
  • delay: the delay/interval in ms between two “ticks” of the stopwatch. This defines the accuracy of the stopwatch. Per default it will be set to 100ms.
  • value: the number of milliseconds the stopwatch has been running for. Initialised to 0ms.
  • display: the HTML element where the stopwatch value will be displayed.

Here is the JavaScript code of our stopwatch so far:

class Stopwatch {
  constructor(id, delay=100) { //Delay in ms
    this.state = "paused";
    this.delay = delay;
    this.display = document.getElementById(id);
    this.value = 0;
  }
}

We can then create an HTML element (DIV tag) that will be used to display the stopwatch value.

<div id="stopwatch">00:00:00.0</div>

We can then create a stopwatch object/instance of the Stopwatch class as follows:

stopwatch = new Stopwatch("stopwatch");

When creating our stopwatch object, the constructor of the class is automatically called to initialise the stopwatch.

At this stage nothing happens yet, as we have not defined any behaviours/methods to our Stopwatch class.

Notice the naming convention: when creating classes and objects it is good practice for the identifier of a class to start with an uppercase letter (e.g. Stopwatch) whereas identifiers used for objects start with a lowercase letter (e.g. stopwatch).

Step 2: Adding a few methods

The main methods of our Stopwatch class will be:

  • start(): to start/resume the stopwatch!
  • stop(): to stop/pause the stopwatch
  • reset(): to stop and reset the stopwatch to 0ms.
  • update(): to increment the stopwatch (based on the set delay) and refresh its display with the current value.

The update() method of the stopwatch will use an extra formatTime() method used to convert a number of milliseconds into the HH:MM:SS format.

Here is the full code for the Stopwatch class including all 5 methods:

class Stopwatch {
  constructor(id, delay=100) { //Delay in ms
    this.state = "paused";
    this.delay = delay;
    this.display = document.getElementById(id);
    this.value = 0;
  }
  
  formatTime(ms) {
    var hours   = Math.floor(ms / 3600000);
    var minutes = Math.floor((ms - (hours * 3600000)) / 60000);
    var seconds = Math.floor((ms - (hours * 3600000) - (minutes * 60000)) / 1000);
    var ds = Math.floor((ms - (hours * 3600000) - (minutes * 60000) - (seconds * 1000))/100);

    if (hours   < 10) {hours   = "0"+hours;}
    if (minutes < 10) {minutes = "0"+minutes;}
    if (seconds < 10) {seconds = "0"+seconds;}
    return hours+':'+minutes+':'+seconds+'.'+ds;
  }
  
  update() {
    if (this.state=="running") {
      this.value += this.delay;
    }
    this.display.innerHTML = this.formatTime(this.value);
  }
  
  start() {
    if (this.state=="paused") {
      this.state="running";
      if (!this.interval) {
        var t=this;
        this.interval = setInterval(function(){t.update();}, this.delay);
      }
    }
  }
  
  stop() {
       if (this.state=="running") {
      this.state="paused";
    if (this.interval) {
      clearInterval(this.interval);
      this.interval = null;
    }
       }
  }
  
  reset() {
    this.stop();
    this.value=0;
    this.update();
  }
}

Note that the setInterval() function used in the start() method is used to constantly call the update() method at the specified interval/delay (in milliseconds).

Step 3: Using the stopwatch object

We have already (see step 1) created our stopwatch object using the following JavaScript code:

stopwatch = new Stopwatch("stopwatch");

We can now add three buttons in HTML to trigger the start(), stop() and reset() methods of our object:

<div id="stopwatch">00:00:00.0</div>
<button onclick="stopwatch.start();">Start</button> 
<button onClick="stopwatch.stop();">Stop</button>
<button onClick="stopwatch.reset();">Reset</button>
</div>

HTML – CSS & JavaScript Code

Here is the full code for our stopwatch with some extra CSS to improve the look & feel of our stopwatch.

See the Pen
Stopwatch Class
by 101 Computing (@101Computing)
on CodePen.

Your Challenge

Your challenge is to adapt this code to create a new timer class.
The timer will have the same look & feel as the stopwatch, but instead of counting up, it will count down from a pre-set time (e.g. 1 minute timer, 5 minute timer). The user should be able to set the pre-set time for the timer and start/pause/reset the timer using control buttons. The timer should automatically stop when it reaches 00:00:00.0.

Did you like this challenge?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 6

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!

Tagged with: