简体   繁体   English

多个ajax请求的速率限制

[英]Rate limiting with multiple ajax requests

I'm trying to ratelimit my ajax requests in order to remain within api limits. 我试图对我的Ajax请求进行速率限制,以保持在api限制内。 I make one request to my server which returns a list of data. 我向服务器发出一个请求,该服务器返回数据列表。 From that list of data, I make a request to an api which does not allow receiving more than one request per second. 从该数据列表中,我向一个api发送请求,该请求不允许每秒接收多个请求。 How can I use setTimeout or a similar function to limit my requests? 如何使用setTimeout或类似的函数限制请求?

myArray = ['1','2','3'];

function f1(){
    for (var num in myArray){
        $.ajax({
            type: "POST",
            url: "backend.php",
            data: {suburbs : num}, 
            success: function(data){
                for (var item in data){
                    f2(data[item])
                }
            }
        });
    }
}

function f2(text) {
    $.getJSON("http://example.com/test.html?" + text, null, function (data) {
        console.log(data)
    }
}

Just create a list of functions: 只需创建功能列表:

var duration = 1000; // API duration
var expectAsync = 3000; // time to wait for new functions;
var lastCall = Date.now();
var myArray = ['1','2','3'];
function queryArray() {
  var fnList = [];
  myArray.forEach(function(v){
    fnList.push( function() { // push f1 to list;
       $.ajax({
        type: "POST",
        url: "backend.php",
        data: {suburbs : v}, 
        success: function(data){
            fnList.push(function(){ // push f2, after we get response;
              for (var item in data){
                f2(data[item]);
              }
            })

        }
    })
  });
  // here we go;
  var int;
  int = setInverval(function(){
    if(fnList.length){
      var fn = fnList.shift(); // pop first function from left;
      fn();
    }else{
      if((Date.now() - lastCall) > expectAsync) clearInterval(int); 
    }
    lastCall = Date.now();
  }, duration);
}

setTimeout does not work like java's sleep. setTimeout不能像java的睡眠一样工作。 It is asynchronous with a callback. 它与回调异步。 After the time is up, the callback function get triggered, which means that you want to put your request into the callback function. 时间到后,将触发回调函数,这意味着您要将请求放入回调函数。

myArray = ['1','2','3'];

function f1(){
    for (var i = 0; i < myArray.length; i++){
        $.ajax({
            type: "POST",
            url: "backend.php",
            data: {suburbs : myArray[i]}, 
            success: function(data){
                for (var j = 0; j < data.length; j++){
                    setTimeout(function() {
                       f2(data[j]);
                    }, (i*data.length + j)*1000);
                }
            }
        });
    }
}

In the for loop, you need to use the index to determine how long you need to wait. 在for循环中,您需要使用索引来确定需要等待多长时间。 After the request is triggered. 触发请求后。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM