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
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.
I would highly recommend this plugin for throttling Ajax requests: http://benalman.com/projects/jquery-throttle-debounce-plugin/
jQuery has a .delay() and .queue() interface I suggest you checkout and read about.
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);
})();
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
}
});
});