Pages

Tuesday, October 4, 2016

Timer (JavaScript)

/*
 * Timer is a constructor function that may be
 * used to produces instances of objects of 
 * type Timer. An object of type Timer has
 * methods start() and stop() that start
 * and stop a timer, a method called reset
 * that resets a timer, and a method called
 * elaspedTimeInMs that returns an amount of
 * elapsed time. If a timer has been started
 * but not stopped, then elapsedTimeInMs
 * returns the amount of time (in milliseconds)
 * that has elapsed since the timer was started.
 * If a timer has been started and stopped,
 * then elapsedTimeInMs returns the amount of
 * time that elapsed between the time the
 * timer was started and stopped.
 */
function Timer() {
  this.reset();
}
Timer.prototype = {
  reset: function() {
    this.timeStarted = null;
    this.timeStopped = null;
  },
  start: function() {
    this.timeStarted = new Date();
  },
  stop: function() {
    this.timeStopped = new Date();
  },
  elapsedTimeInMs() {
    if (this.timeStarted != null) {
      if (this.timeStopped != null) {
        return this.timeStopped - this.timeStarted;
      }
      else {
        return new Date() - this.timeStarted;
      }
    }
    else {
      return undefined;
    }
  }
};