Skip to content

Instantly share code, notes, and snippets.

@andrewvmail
Forked from manast/interval.js
Created June 26, 2019 06:34
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 andrewvmail/2c5681b2016be86c15c8a5e18e3cffca to your computer and use it in GitHub Desktop.
Save andrewvmail/2c5681b2016be86c15c8a5e18e3cffca to your computer and use it in GitHub Desktop.
Accurate Javascript setInterval replacement
function interval(duration, fn){
this.baseline = undefined
this.run = function(){
if(this.baseline === undefined){
this.baseline = new Date().getTime()
}
fn()
var end = new Date().getTime()
this.baseline += duration
var nextTick = duration - (end - this.baseline)
if(nextTick<0){
nextTick = 0
}
(function(i){
i.timer = setTimeout(function(){
i.run(end)
}, nextTick)
}(this))
}
this.stop = function(){
clearTimeout(this.timer)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment