Skip to content

Instantly share code, notes, and snippets.

@tkh44
Created November 6, 2013 22:03
Show Gist options
  • Select an option

  • Save tkh44/7344910 to your computer and use it in GitHub Desktop.

Select an option

Save tkh44/7344910 to your computer and use it in GitHub Desktop.
Run a function repeatedly on a specific interval
/**
* Run a function repeatedly on a specific interval
* @param {function} fn callback to run
* @param {number} interval time in ms between runs
* @param {boolean} immediate
* @param {...n} args
* @returns {object} timer object. Call cancel() to stop timer
*/
later: function(fn, interval, immediate, args) {
var cbArgs = _.toArray(arguments).slice(3);
if (immediate) {
fn.apply(this, cbArgs); // Run once immediately
}
var wrapper = function() {
fn.apply(this, cbArgs);
}
var timeoutId = setInterval(wrapper, interval);
return {
timeoutId: timeoutId,
cancel: function() {
clearInterval(timeoutId);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment