Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const Stopwatch = function () {
- let states = { "reset": 0, "started": 1, "stopped": 2 }
- let startTime, endTime, duration, currentState
- this.start = function () {
- if (currentState === states["started"])
- throw new Error("Stopwatch has already started.")
- currentState = states["started"]
- startTime = Date.now()
- return "started..."
- }
- this.stop = function () {
- if (currentState !== states["started"])
- throw new Error("Stopwatch is not started.")
- currentState = states["stopped"]
- endTime = Date.now()
- return "stopped..."
- }
- this.reset = function () {
- startTime = undefined
- endTime = undefined
- duration = undefined
- currentState = states["reset"]
- return "reset..."
- }
- Object.defineProperty(this, "duration", {
- get: function () {
- if (currentState === states["stopped"])
- return (endTime - startTime) / 1000
- else if (currentState === states["started"])
- throw new Error("Clock has not been stopped.")
- else
- throw new Error("Clock has not been started yet.")
- }
- })
- }
Add Comment
Please, Sign In to add comment