Created
August 3, 2018 17:43
-
-
Save cmccormack/101b855f493d2477e24cd5dddac389c4 to your computer and use it in GitHub Desktop.
A more accurate timer to replace setInterval
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
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