Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery throttling and queuing of AJAX requests

Tags:

jquery

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()?

Much obliged!

like image 440
FLX Avatar asked Aug 16 '11 17:08

FLX


4 Answers

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
        }
    });
});
like image 132
John Kalberer Avatar answered Nov 01 '22 03:11

John Kalberer


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

like image 3
Chad Avatar answered Nov 01 '22 03:11

Chad


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

like image 1
Chris Laplante Avatar answered Nov 01 '22 03:11

Chris Laplante


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);
})();
like image 1
Matt Avatar answered Nov 01 '22 02:11

Matt