I need to access an API but I dont want to shoot with 100 requests at the same time so I want to make 1 request per second so I write:
$.each(added_collections, function(index, collection) {
$.each(collection, function(index1, page) {
$.each(page, function(index2, product) {
setTimeout(function() {
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: "POST",
url: '/get_data',
dataType: "json",
data: meta_data,
success: function(data) {
console.log(data);
},
error: function(data){
console.log(data);
}
});
}, 1000);
});
});
});
but this code do not make 1second between requests
How I can make 1 ajax call per second
2
Answers
I’m not sure what data you need to be in that ajax call, but here’s a way to throttle in the manner you’re after. Build the array of indexes (products) first. Then use a separate helper function to call the ajax and call itself again recursively when complete.
Ideally you want to use a throttle function of some kind. You can use a library for this, or can write a simple one which may work for your use case like this (this technique can be used for other functions as well)
Then to use it with your Ajax method, something like this
The reason the calls all happen at about the same time in your code is all the timeouts begin at about the same time. Ie between each iteration of the loop, basically no time passes, so the timers all end 1 second later.