Skip to content

Instantly share code, notes, and snippets.

@thelinuxlich
Created March 12, 2014 17:35
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 thelinuxlich/9512013 to your computer and use it in GitHub Desktop.
Save thelinuxlich/9512013 to your computer and use it in GitHub Desktop.
var throttler = function(fn, maxExecutions) {
var counter = 0,
queue = [];
return function() {
var self = this,
args = arguments,
old_callback = args[args.length - 1];
args[args.length - 1] = function() {
counter -= 1;
if(counter < maxExecutions && queue.length > 0) {
counter += 1;
fn.apply(self, queue.shift());
}
old_callback.apply(self, arguments);
};
if(counter < maxExecutions) {
counter += 1;
fn.apply(self, args);
} else {
queue.push(args);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment