Skip to content

Instantly share code, notes, and snippets.

@Ovi
Created August 8, 2022 16:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ovi/47e15e6c872ef71de37b7cf410870113 to your computer and use it in GitHub Desktop.
Save Ovi/47e15e6c872ef71de37b7cf410870113 to your computer and use it in GitHub Desktop.
Simple Javascript Stopwatch constructor
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