Skip to content

Instantly share code, notes, and snippets.

@mwcz
Created February 11, 2016 15:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mwcz/5b95b653d410b01bb367 to your computer and use it in GitHub Desktop.
Save mwcz/5b95b653d410b01bb367 to your computer and use it in GitHub Desktop.
nth function, execute a function every nth invocation
/**
* Wrap your function such that it will be executed every N times it's called.
* This is useful in a long-running loop such as the main loop in a game, where
* you want to execute certain functions every 10 frames, or similar, but don't
* want to manage a dozen separate "timers".
*
* @param {Function} f the function to wrap
* @param {Number} n execute the function every `n` times
*/
function nth(f, n) {
var _i = 0;
var _n = Math.max(n, 0);
return function() {
if (_i === _n) {
_i = 0;
return f.apply(this, arguments);
}
else {
_i++;
}
}
}
// function ping() { return 'ping!!!' }
//
// var ping_sample = nth( ping, 3 );
//
// ping_sample(); // returns: undefined
// ping_sample(); // returns: undefined
// ping_sample(); // returns: ping!!!
// ping_sample(); // returns: undefined
// ping_sample(); // returns: undefined
// ping_sample(); // returns: ping!!!
// ping_sample(); // returns: undefined
// ping_sample(); // returns: undefined
// ping_sample(); // returns: ping!!!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment