Skip to content

Instantly share code, notes, and snippets.

@dr-skot
Created April 23, 2021 16:17
Show Gist options
  • Save dr-skot/bd2688bfe0b90b559779d4a4a646e87c to your computer and use it in GitHub Desktop.
Save dr-skot/bd2688bfe0b90b559779d4a4a646e87c to your computer and use it in GitHub Desktop.
Basic javascript stopwatch object
function StopWatch() {
let started = Date.now(),
time = 0,
running = false;
function getTime() {
return running ? Date.now() - started : time;
}
function start() {
if (!running) {
started = Date.now() - time;
running = true;
}
}
function stop() {
if (running) {
time = getTime();
running = false;
}
}
function toggle() {
(running ? stop : start)();
}
function reset() {
started = Date.now();
time = 0;
}
return {
getTime,
start,
stop,
toggle,
reset,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment