Note: The Console blog is no longer active. I'm currently building the Sculpted Code blog, and when it's finished, I shall be posting there.
← Console Index
How to Create a Simple Timer in JavaScript

Since I’m going to release my QQTimer class soon, I thought it would be an appropriate time to write a little tutorial on how to create a simple timer in JavaScript.

The idea is simple: we record the current time when the user starts the timer, record the current time when the user stops the timer, and then subtract the two to find out how much time has elapsed.

The trick is to get both numbers into a format on which we can perform standard mathematical calculations. The JavaScript method getTime() works well for this, as it returns the number of milliseconds since 1 January 1970.

First, we create our class “Timer”:

function Timer() {}

We’ll have have three instance variables:

  • startTime – This will store the time when we start the timer
  • stopTime – This will store the time when we stop the timer
  • stopped – This will store a boolean indicating whether the timer has been stopped or not

Here’s what our completed object constructor function looks like:

function Timer()
{
 this.startTime = 0;
 this.stopTime = 0;
 this.stopped = true;
}

Now we’ll add three methods:

  • start() – This will start the timer
  • stop() – This will stop the timer
  • getElapsedTime() – If the timer has been stopped, then this will get the elapsed time between when the timer was started and when it was stopped; if the timer hasn’t been stopped yet, it will get the elapsed time since the timer was started
  • clear() – This will reset all the values

The start method will simply set this.startTime to the value of the getTime() method:

Timer.prototype.start = function()
{
 var currentDate = new Date();
 this.startTime = currentDate.getTime();
}

The stop method is almost identical to the start method, except that this time we set this.stopTime to the value of the getTime() method:

Timer.prototype.stop = function()
{
 var currentDate = new Date();
 this.stopTime = currentDate.getTime();
}

The getElapsedTime method will check whether the timer has been stopped or not, then return either the start time subtracted from the stop time, or the start time subtracted from the current time (respectively):

Timer.prototype.getElapsedTime = function()
{
 if (this.stopped) {
  return (this.stopTime - this.startTime)
 }
 else {
  var currentDate = new Date();
  return (currentDate.getTime() - this.startTime)
 }
}

Finally, the clear: method resets all our instance variables. It is exactly the same code as in the initialisation function:

Timer.prototype.clear = function()
{
 this.startTime = 0;
 this.stopTime = 0;
 this.stopped = true;
}

And that’s it. You’ve now created a simple timer class using JavaScript!