Created
September 26, 2011 00:46
-
-
Save neopunisher/1241381 to your computer and use it in GitHub Desktop.
A function to mixin to _ that throttles API calls
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
_.mixin({throttleApi:function(m,g,h,d){var j=function(a){var i=new Date;_.isUndefined(a)||i.setSeconds(i.getSeconds()+a);return i},b=[],e=0,f=0,c=null,l=j(1),k=function(a){console.log("rundo");if(b.length==0)console.log("queue empty".yellow),clearTimeout(c),c=null;else{a=[];if(g){l<j()&&(console.log("reset timer...".yellow),f=0,l=j(1));if(f==g)return;a.push(g-f)}if(h){if(e==h)return;a.push(h-e)}a.push(b.length);a=_.min(a);console.log("i run:"+a);_.times(a,function(){f++;e++;var a=b.shift();_.isUndefined(d)&& | |
(d=_.compact(_.map(a,function(a,b){return _.isFunction(a)?b:!1}))[0]);var c=a[d];a[d]=function(){e--;b.length>0&&_.defer(k);c.apply(this,_.toArray(arguments))};m.apply(null,a)});_.isNull(c)&&b.length>0&&(console.log("setting timer".yellow),c=setInterval(k,500))}};return function(){console.log("pushing args".yellow);b.length==0&&_.defer(k);b.push(_.toArray(arguments))}}}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment