AngularJS 1.1.5 (this is considered the unstable release) provides support for both request and response interceptors. The concepts are pretty similar to what's being done via the angular-http-auth interceptor module (https://github.com/witoldsz/angular-http-auth)
The following http-throttler service can be injected into your code to throttle your HTTP requests. Wire it into Angular when you define your app.
Example:
angular.module('myApp', ['http-throttler'])
.config(['$routeProvider','$httpProvider', function($routeProvider, $httpProvider) {
$httpProvider.interceptors.push('httpThrottler');
$routeProvider.
when('.............your stuff here..........')
...........more of your stuff....
});
Put this in http-interceptor.js and include it in your application.
(function() {
"use strict"; angular.module('http-throttler', ['http-interceptor-buffer']).factory("httpThrottler", ['$q', '$log', 'httpBuffer', function($q, $log, httpBuffer) {
var reqCount, service;
reqCount = 0;
service = {
request: function(config) {
var deferred;
$log.info("Incoming Request - current count = " + reqCount);
if (reqCount >= 10) {
$log.warn("Too many requests");
deferred = $q.defer();
httpBuffer.append(config, deferred);
return deferred.promise;
} else {
reqCount++;
return config || $q.when(config);
}
},
response: function(response) {
$log.info("Response received from server");
reqCount--;
httpBuffer.retryOne();
return response || $q.when(response);
}
};
return service;
}
]);
angular.module('http-interceptor-buffer', []).factory('httpBuffer', [
'$log', function($log) {
var buffer, retryHttpRequest, service;
buffer = [];
retryHttpRequest = function(config, deferred) {
if (config != null) {
$log.info("Resolving config promise");
return deferred.resolve(config);
}
};
service = {
append: function(config, deferred) {
return buffer.push({
config: config,
deferred: deferred
});
},
retryOne: function() {
var req;
if (buffer.length > 0) {
req = buffer.pop();
return retryHttpRequest(req.config, req.deferred);
}
}
};
return service;
}
]);
}).call(this);
Above, it's hard coded to 10 per your question. I may make this configurable and push it up on GitHub in case others find it useful.
Again - this does not work in the 1.0.7 release of AngularJS, since 1.0.7 does not support the new interceptors array on $httpProvider. It only supports responseInterceptors. I haven't tried 1.1.4, but this appears to work reasonably well in 1.1.5.
Code available on GitHub @ https://github.com/mikepugh/angular-http-throttler