jQuery限制和排队AJAX请求 [英] jQuery throttling and queuing of AJAX requests

查看:81
本文介绍了jQuery限制和排队AJAX请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 that are made against an API by using .ajax()?

有义务!

推荐答案

您可以按照以下方式做些事情

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

这篇关于jQuery限制和排队AJAX请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆