jQuery throttling and queuing of AJAX requests

后端 未结 5 1598
庸人自扰
庸人自扰 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:10

    If you want to ensure anything then you'd best get a medium other than the internet - it is inherently unreliable. Anyway, in order to try to ensure, you could use the Javascript setTimeout method to initiate the call at a later time.

    Other than that, if you don't want to use any other third party resources, you could look into the delay method exposed by jQuery.

    0 讨论(0)
  • 2021-01-04 12:18

    I would highly recommend this plugin for throttling Ajax requests: http://benalman.com/projects/jquery-throttle-debounce-plugin/

    0 讨论(0)
  • 2021-01-04 12:25

    jQuery has a .delay() and .queue() interface I suggest you checkout and read about.

    0 讨论(0)
  • 2021-01-04 12:28

    This is a shorter solution and doesn't throttle the first call put into the queue.

    let ajaxQueue = [];
    let ajaxQueueTime = 2000;
    

    Execute your ajax calls like this.

    requests.push(function() {
        $.get(url, function(rsp) {
            console.log("Hello");
        });
    });
    

    This is the routine that processes the ajax call queue.

    (function throttleAjax() {
        if (ajaxQueue.length > 0) ajaxQueue.pop()();
        setTimeout(throttleAjax, ajaxQueueTime);
    })();
    
    0 讨论(0)
  • 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
            }
        });
    });
    
    0 讨论(0)
提交回复
热议问题