Created
March 12, 2014 17:35
-
-
Save thelinuxlich/9512013 to your computer and use it in GitHub Desktop.
This file contains 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
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