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!
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 has a .delay() and .queue() interface I suggest you checkout and read about.
I would highly recommend this plugin for throttling Ajax requests: http://benalman.com/projects/jquery-throttle-debounce-plugin/
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);
})();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With