JSFiddle - React, Tailwind, and code Playground

by Santosh Giridhara

JavaScript

function stopWatch() {
  let startTime, stopTime, running, duration = 0;

  Object.defineProperty(this, 'duration', {
    get: function() {
      return duration;
    },
    set: function(value) {
      duration = value;
    }
  });
  Object.defineProperty(this, 'startTime', {
    get: function() {
      return startTime;
    },
    set: function(value) {
      startTime = value;
    }
  });
  Object.defineProperty(this, 'stopTime', {
    get: function() {
      return stopTime;
    },
    set: function(value) {
      stopTime = value;
    }
  });
  Object.defineProperty(this, 'running', {
    get: function() {
      return running;
    },
    set: function(value) {
      running = value;
    }
  });
}

stopWatch.prototype.start = function() {
  if (this.running) {
    throw new Error('Stopwatch is already started');
  }
  this.running = true;
  this.startTime = new Date();

};

stopWatch.prototype.stop = function() {
  if (!this.running) {
    throw new Error('Stopwatch is already stopped');
  }
  this.running = false;
  this.endTime = new Date();
  const seconds = (this.endTime.getTime() - this.startTime.getTime()) / 1000;
  this.duration = this.duration + seconds;
};

stopWatch.prototype.reset = function() {
  this.startTime = null;
  this.stopTime = null;
  this.duration = 0;
  this.running = false;
};

let sw = new stopWatch();