Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@cmccormack
Created August 3, 2018 17:43
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 cmccormack/101b855f493d2477e24cd5dddac389c4 to your computer and use it in GitHub Desktop.
Save cmccormack/101b855f493d2477e24cd5dddac389c4 to your computer and use it in GitHub Desktop.
A more accurate timer to replace setInterval
class AccurateInterval {
intervalId = null
constructor(fn, timer) {
this.fn = fn
this.timer = timer
}
start = () => {
this.next = new Date().getTime() + this.timer
this.step()
return this
}
step = () => {
this.next += this.timer
this.intervalId = setTimeout(() => {
this.step()
this.fn()
},
this.next - new Date().getTime())
}
stop = () => {
clearTimeout(this.intervalId)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment