Skip to content

Instantly share code, notes, and snippets.

@tungpham42
Forked from manast/interval.js
Created December 15, 2017 07:40
Show Gist options
  • Save tungpham42/77f1467a9d20cbf04125b992a7a87e82 to your computer and use it in GitHub Desktop.
Save tungpham42/77f1467a9d20cbf04125b992a7a87e82 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)
}
}
@tungpham42
Copy link
Author

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