Created
April 23, 2021 16:17
-
-
Save dr-skot/bd2688bfe0b90b559779d4a4a646e87c to your computer and use it in GitHub Desktop.
Basic javascript stopwatch object
This file contains hidden or 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 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