简体   繁体   English

jQuery限制同时AJAX请求的数量

[英]jQuery Limit The Number Of Simultaneous AJAX Requests

so I have a series of AJAX events I would like to fire, but I want to limit the number of simultaneous requests to 5, and queue up the rest. 所以我想要触发一系列AJAX事件,但是我想将同时请求的数量限制为5,并将剩下的请求排队。 So for example, I have the following: 例如,我有以下内容:

 $("div.server").each(function() {
     $.ajax(....);
 });

So there may be 100 divs with the class server , but I want to only run 5 requests at any given time. 因此类server可能有100个div,但我想在任何给定时间只运行5个请求。 Once a request finishes it should proceed to the next. 一旦请求完成,它应该继续下一个。

What is the best way to do this? 做这个的最好方式是什么?

The best way to do this is letting the browser deal with it. 最好的方法是让浏览器处理它。 Usually browsers already have a per-host connection limit so they will automatically queue connections if there are too many. 通常,浏览器已经具有每主机连接限制,因此如果存在太多,它们将自动对连接进行排队。

However, I'd consider changing the API so it takes date from multiple elements and also returns data for multiple elements - ie reducing the overall count of HTTP requests necessary. 但是,我会考虑更改API,以便从多个元素中获取日期,并返回多个元素的数据 - 即减少必要的HTTP请求的总数。

Push all request arguments to a queue with a function called queueRequest and call checkQueue . 使用名为queueRequest的函数将所有请求参数推送到队列并调用checkQueue checkQueue checks to see if there are items in the queue and if the number of active requests is less than 5. If these conditions are met, it pops a request from the queue and turns it into a real AJAX request. checkQueue检查队列中是否有项目以及活动请求的数量是否小于5.如果满足这些条件,它会从队列中弹出一个请求并将其转换为真正的AJAX请求。 Then it attaches a done handler to the request that decreases the active request count and calls checkQueue . 然后它将一个done处理程序附加到请求,减少活动请求计数并调用checkQueue

If still unsure about the browser's capabilities in queueing the requests, you could try something like this: 如果仍然不确定浏览器排队请求的功能,你可以尝试这样的事情:

var count = 0;          // Number of functions being called
var funcArray = [];     // Array of functions waiting
var MAX_REQUESTS = 5;   // Max requests
var CALL_WAIT = 100;        // 100ms

function call()
{
    // Check if count doesn't exceeds or if there aren't any functions to call
    if(count >= MAX_REQUESTS || funcArray.length == 0)
        // Call call() after 100ms
        setTimeout(function() { call() }, CALL_WAIT);
    count++;            // Add request to the counter
    var func = funcArray.pop();
    $.ajax(..., function(data)
    {
        func(data);
        // .......
        count--;        // Substract request to the counter
    });
}

$(function()
{
    call();     // First call to start polling. It will call itself each 100ms
});

$(function()
{
    $("div.server").each(function() {
         funcArray.push(function(data)
         {
            alert(data);
         });
     });
});

You may have to tweak it for your needs. 您可能需要根据需要进行调整。

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

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