Skip to content

Instantly share code, notes, and snippets.

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 lsauer/01a90c5a293598ec6668 to your computer and use it in GitHub Desktop.
Save lsauer/01a90c5a293598ec6668 to your computer and use it in GitHub Desktop.
Custom scoped setInterval and repeat for n-times: intervalCallNtimes binds a function to a declared scope and invokes it after 'tm' milliseconds for n-times
//lsauer.com, 2012 lo sauer
//description: intervalCallNtimes; counter after nth time clearinterval; bind a function to a certain scope using 'intervalCall'
//requires: intervalCall, see: https://gist.github.com/lsauer/cf70e65c208cc311ce97
//@param fntimes: an integer-Number or function to control the number of invocations of the callback-counter-function:'fntimes'
// fntimes is passed an integer Number-counter, starting at 1;
//@param fn: the function to be invoked
//@param tm: timeout in milliseconds
//@param scope: scope in which the function should be invoked
//-> examples are provided below
function intervalCallNtimes(fntimes, fn, tm, scope){
if( NaN === parseFloat(fntimes) && typeof fntimes !== 'function' ){
throw new TypeError("timer-argument must be of Type 'Number' or 'Function'; Type" + fntimes); };
var _fntimes = fntimes;
//Example-timer-stop function
if(typeof fntimes !== 'function') {
var _cnt = fntimes;
var _fntimes = function(i){ if(i > _cnt){return clearInterval(_ifn); } };
}
var _ifn = intervalCall(scope||this, fn, tm||1000, _fntimes);
return _ifn;
}
//lsauer.com, 2012 lo sauer
//example-code: invoke a function five times in the scope 'document':
//example #1:
var _ifn = intervalCallNtimes(
function(i){ console.log(i); if(i >= 5){clearInterval(_ifn); } },
function(){console.log("test", this)},
500,
document);
//example #2:
var _ifn = intervalCallNtimes( 4, function(){console.log("test")})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment