Skip to content

Instantly share code, notes, and snippets.

@Ivannnnn
Last active December 12, 2021 13:30
Show Gist options
  • Save Ivannnnn/8f5b7fbf80dc4a233ed29a3c183a51c7 to your computer and use it in GitHub Desktop.
Save Ivannnnn/8f5b7fbf80dc4a233ed29a3c183a51c7 to your computer and use it in GitHub Desktop.
Timer
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