stopwatch

by Pritesh Patel

JavaScript

function stopWatch() {
	let startTime, endTime, running, duration = 0;
	this.start = function() {
  	if (running) {
    	throw new Error('Stop watch is already running');
    }
    	running = true;
  	startTime = new Date().getTime();
  };
  this.stop = function() {
  	 if (!running) {
    	throw new Error('Stop watch is not running');
    }
    running = false;
  	endTime = new Date().getTime();
    const seconds = (endTime - startTime) / 1000;
    duration += seconds;
   
  };
  this.reset = function() {
  	startTime = null;
    endTime = null;
    running = false;
    duration = 0;
  };
  
  Object.defineProperty(this, 'duration', {
  	get: function() { return duration }
  });
}