Skip to content

Instantly share code, notes, and snippets.

@englishextra
Forked from manast/interval.js
Last active May 17, 2016 09:41
Show Gist options
  • Save englishextra/f721a0c4d12aa30f74c2e089370e09eb to your computer and use it in GitHub Desktop.
Save englishextra/f721a0c4d12aa30f74c2e089370e09eb to your computer and use it in GitHub Desktop.
Accurate Javascript setInterval replacement
/*!
* Accurate Javascript setInterval replacement
* gist.github.com/manast/1185904
* gist.github.com/englishextra/f721a0c4d12aa30f74c2e089370e09eb
* minified with closure-compiler.appspot.com/home
* var timer = new interval(50, function(){ if(1===1){timer.stop(), timer = 0;}}); timer.run();
* The handle will be a number that isn't equal to 0; therefore, 0 makes a handy flag value for "no timer set".
* stackoverflow.com/questions/5978519/setinterval-and-how-to-use-clearinterval
*/
function interval(d,f){this.baseline=void 0;this.run=function(){void 0===this.baseline&&(this.baseline=(new Date).getTime());f();var c=(new Date).getTime();this.baseline+=d;var b=d-(c-this.baseline);0>b&&(b=0);(function(d){d.timer=setTimeout(function(){d.run(c)},b)}(this))};this.stop=function(){clearTimeout(this.timer)}};
@englishextra
Copy link
Author

englishextra commented May 17, 2016

The handle will be a number that isn't equal to 0; therefore, 0 makes a handy flag value for "no timer set".
http://stackoverflow.com/questions/5978519/setinterval-and-how-to-use-clearinterval

var handle = setInterval(drawAll, 20);
// When you want to cancel it:
clearInterval(handle);
handle = 0;

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