-
-
Save sessa/2963060 to your computer and use it in GitHub Desktop.
Accurate Javascript setInterval replacement
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
interval: function (duration, callback){ | |
var baseline = undefined; | |
return { | |
run: function() { | |
if( baseline === undefined ) { | |
baseline = new Date().getTime(); | |
} | |
callback(); | |
var end = new Date().getTime(); | |
baseline += duration; | |
var nextTick = duration - (end - baseline); | |
if( nextTick < 0 ) { | |
nextTick = 0; | |
} | |
(function(i) { | |
i.timer = setTimeout(function(){ | |
i.run( end ); | |
}, nextTick) | |
}(this)); | |
}, | |
stop: function() { | |
clearTimeout( this.timer ); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A little more modular for util libs. Also more standardized JS syntax / coding standards.