Skip to content

Instantly share code, notes, and snippets.

@adamcbrewer
Created November 21, 2013 12:50
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamcbrewer/7581035 to your computer and use it in GitHub Desktop.
Save adamcbrewer/7581035 to your computer and use it in GitHub Desktop.
JS: A better interval handler
/**
* setInterval has some issues:
* 1. Doesn't care whether the callback is still running or not
* 2. Ignores errors
*
* @source http://www.thecodeship.com/web-development/alternative-to-javascript-evil-setinterval/
* @param func The function to call
* @param wait The interval to wait
* @param times The total number of repititions, instead of infinite
*
*/
function interval(func, wait, times){
var interv = function(w, t){
return function(){
if(typeof t === "undefined" || t-- > 0){
setTimeout(interv, w);
try{
func.call(null);
}
catch(e){
t = 0;
throw e.toString();
}
}
};
}(wait, times);
setTimeout(interv, wait);
};
// Usage:
interval(function(){
// Code block goes here
}, 1000, 10);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment