This code factors the throttling code into a throttled function constructor.
function makeLimited(fn, count) { var queue = []; var outstanding = 0; return function() { var args = Array.prototype.slice.call(arguments, 0); // replace the last arg by one that runs the // next queued fn args.push(adviseAfter(args.pop(), next)); if (outstanding < count) { outstanding++; fn.apply(this, args); } else queue.push(args); } function next() { if (queue.length) fn.apply(null, queue.shift()); } }
$.throttled = makeLimited($.get, 2);
for (var i = 0; i < 10; i++) $.throttled('services/sleep/2', log);
function adviseAfter(fn, afterfn) { return function() { var result = fn.apply(this, arguments); afterfn.apply(this, arguments); return result; } }