Skip to content

Instantly share code, notes, and snippets.

@sessa
Forked from manast/interval.js
Created June 21, 2012 00:07
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sessa/2963060 to your computer and use it in GitHub Desktop.
Save sessa/2963060 to your computer and use it in GitHub Desktop.
Accurate Javascript setInterval replacement
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 );
}
}
}
@sessa
Copy link
Author

sessa commented Jun 21, 2012

A little more modular for util libs. Also more standardized JS syntax / coding standards.

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