fueanta

Stopwatch in JS (Constructor Function)

Apr 16th, 2020
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const Stopwatch = function () {
  2.     let states = { "reset": 0, "started": 1, "stopped": 2 }
  3.     let startTime, endTime, duration, currentState
  4.  
  5.     this.start = function () {
  6.         if (currentState === states["started"])
  7.             throw new Error("Stopwatch has already started.")
  8.  
  9.         currentState = states["started"]
  10.         startTime = Date.now()
  11.  
  12.         return "started..."
  13.     }
  14.  
  15.     this.stop = function () {
  16.         if (currentState !== states["started"])
  17.             throw new Error("Stopwatch is not started.")
  18.  
  19.         currentState = states["stopped"]
  20.         endTime = Date.now()
  21.  
  22.         return "stopped..."
  23.     }
  24.  
  25.     this.reset = function () {
  26.         startTime = undefined
  27.         endTime = undefined
  28.         duration = undefined
  29.         currentState = states["reset"]
  30.  
  31.         return "reset..."
  32.     }
  33.  
  34.     Object.defineProperty(this, "duration", {
  35.         get: function () {
  36.             if (currentState === states["stopped"])
  37.                 return (endTime - startTime) / 1000
  38.             else if (currentState === states["started"])
  39.                 throw new Error("Clock has not been stopped.")
  40.             else
  41.                 throw new Error("Clock has not been started yet.")
  42.         }
  43.     })
  44. }
Add Comment
Please, Sign In to add comment