jQuery限制和排队的AJAX请求

FLX*_*FLX 11 jquery

我正在与一个允许每5秒执行一次操作的API进行交互.但是,我想确保所有请求都以主机结束.如何使用.ajax()对针对API的请求进行排队和限制?

非常感谢!

Joh*_*rer 11

你可以沿着这些方向做点什么

var requests = [];

setInterval(function() {
    if(requests.length > 0) {
        var request = requests.pop();
        if(typeof request === "function") {
            request();
        }
    }
}, 5000);

// then anywhere you need to make an ajax request
requests.push(function() {
    // ajax request here
    $.ajax({
        url: "/foo", // some variable from outer scope
        success: function(a,b,c) {
            // handle it
        }
    });
});
Run Code Online (Sandbox Code Playgroud)