Last active
December 12, 2021 13:30
-
-
Save Ivannnnn/8f5b7fbf80dc4a233ed29a3c183a51c7 to your computer and use it in GitHub Desktop.
Timer
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
const createInterval = () => { | |
let interval = null | |
const start = (cb, delay) => !interval && (interval = setInterval(cb, delay)) | |
const stop = () => { | |
clearInterval(interval) | |
interval = null | |
} | |
return { start, stop } | |
} | |
const createTimer = (initial, delay = 1000) => { | |
const interval = createInterval() | |
let duration = initial | |
let lastPlay = null | |
const play = (cb) => { | |
interval.start(() => { | |
cb((duration += new Date().getTime() / 1000 - lastPlay)) | |
lastPlay = new Date().getTime() / 1000 | |
}, delay) | |
lastPlay = new Date().getTime() / 1000 | |
} | |
const pause = () => interval.stop() | |
return { play, pause } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment