Created
August 8, 2022 16:31
-
-
Save Ovi/47e15e6c872ef71de37b7cf410870113 to your computer and use it in GitHub Desktop.
Simple Javascript Stopwatch constructor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Stopwatch() { | |
let start, stop, interval; | |
let duration = 0; | |
this.start = function() { | |
if (start) { | |
throw new Error('already started'); | |
} | |
interval = setInterval(() => { | |
duration += 100; | |
}, 100); | |
start = true; | |
stop = false; | |
} | |
this.stop = function() { | |
if (!start) { | |
throw new Error('not started'); | |
} | |
if (stop) { | |
throw new Error('already stopped'); | |
} | |
clearInterval(interval); | |
stop = true; | |
start = false; | |
} | |
this.reset = function() { | |
interval = null; | |
start = false; | |
stop = false; | |
duration = 0; | |
} | |
Object.defineProperty(this, 'duration', { | |
get: function() { | |
return duration / 1000; | |
} | |
}) | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment