jQuery throttling and queuing of AJAX requests

后端 未结 5 1653
庸人自扰
庸人自扰 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条回答
  •  猫巷女王i
    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);
    })();
    

提交回复
热议问题