How can I limit the number of requests per second? There is a certain script and it is necessary that the number of requests does not exceed N, otherwise the server generates an error.

var q = items.reduce(function (prev, item) { return prev.then(function () { return $.ajax({ dataType: 'json', url: 'https://example.com/method/methodOne?callback=?' }).then(function (results_one) { console.log(results_one); return $.ajax({ dataType: 'json', url: 'https://example.com/method/methodTwo?callback=?' }).then(function (results_two) { console.log(results_two); }); }); }); }, $.when([])); 
  • This is done on the server side, not in js. - Visman
  • @Visman, and even when I work with a third-party api resource? - Artemy
  • Are you worried about a series of promises? - Aleksander K.
  • @AleksanderK., Did not quite understand. It bothers me that I may have a lot of requests to the server, but I can only do about 20 per second, and if this limit is exceeded, the server curses. - Artemy
  • @geekartemiy, for example, you can send a request with a delay of 3 seconds - Grundy

2 answers 2

  1. Read triggered queries. For example, before $.ajax() set requestCount += 1 . In this case, requestCount should be visible from all requests;
  2. Before each request, check if the counter has not exceeded the specified threshold. If it is over, we pause for 1 second and after a pause we reset the counter.

A pause can be done like this:

 function sleep(duration) { var defer = $.Deferred(); setTimeout(function() { defer.resolve(); }, duration); return defer.promise(); } 

The result of the execution of sleep() must be returned after inside the function .then()

  • I do not understand, you say that you need to perform the sleep () function before ajax if we hung the threshold and return it at the end of then, and at the end of which then? there are 3 of them. I try and I can't make a stop. - Artemy

You can do something like this:

 function timeoutAjax(conf, timer) { return new Promise(function(resolve, reject) { $.ajax(conf).done(function() { setTimeout(resolve, timer * 1000); }).reject(reject); }); } timeoutAjax(20).then(function() { return timeoutAjax({/* ajax 1 */}, 20); }).then(function() { return timeoutAjax({/* ajax 1 */}, 20); }).then(function() { console.log({/* ajax 1 */}, 3); });