jQuery throttling and queuing of AJAX requests

后端 未结 5 1597
庸人自扰
庸人自扰 2021-01-04 11:42

I\'m interacting with an API that allows one action per 5 seconds. However, I want to ensure all requests end up with the host. How can I queue and throttle the requests tha

5条回答
  •  抹茶落季
    2021-01-04 12:29

    You could do something along these lines

    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
            }
        });
    });
    

提交回复
热议问题