Skip to content

Instantly share code, notes, and snippets.

@ephekt
Forked from manast/interval.js
Created April 25, 2012 20:02
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 ephekt/2492920 to your computer and use it in GitHub Desktop.
Save ephekt/2492920 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)
}
}
@ephekt
Copy link
Author

ephekt commented Apr 25, 2012

This code snippet can be used when a very accurate setInterval is needed. It will always be accurate ( 1+-ms in variance, but the mean will be the exact duration). Of course the function provided must run faster than the duration parameter. If for some reason the function takes more time than the duration in some occasions, the timer will still converge to the exact intervals very fast.

Example of use:

var timer = new interval(50, function(){
console.log(new Date().getTime())
})
timer.run()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment