Created
November 6, 2013 22:03
-
-
Save tkh44/7344910 to your computer and use it in GitHub Desktop.
Run a function repeatedly on a specific interval
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
| /** | |
| * 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