This factors the throttling logic out of $.throttled, into
a constructor that can throttle any function. Now the program
is in three layers: makeThrottled (which is even more complex,
but can be used to throttle any function); $.throttled; and the
application-level code that uses $.throttled.
function makeThrottled(fn, interval) { var queue = []; var nextTime = 0; return function() { queue.push(Array.prototype.slice.call(arguments, 0)); if (queue.length == 1) schedule(); } function schedule() { setTimeout(function() { nextTime = new Date().getTime() + interval; fn.apply(null, queue.shift()); if (queue.length) schedule(); }, Math.max(0, nextTime - new Date().getTime())); } }
$.throttled = makeThrottled($.get, 1000);
for (var i = 0; i < 10; i++) $.throttled('services/time', log);