Hello, I have a service that I am calling an unknown amount of times per each page requests. When the page loads I have a loading spinner running. Before, when I had one ajax requests, I would just stop the loading spinner at the end of that request, usually in the ".done()". Yet this time, I do not know how many calls will happen. I have something like this, for(var i = 0; i < requests_times ; i++){ $.ajax({ url : 'ServiceRequestUrl' }).done() .error() } Now, how would i be able to tell, that when the last ajax request is done, to hide the loading spinner. I have all the requests running asynchronously because they each are populating an area in the website. I know I can use promises, but I can only use it if I know the exact requests being made, for example : $.when( $.ajax('url1'), $.ajax('url2') ).then(function(){ //do something }) If I would be able to pass an array to then $.when object then I believe I would be ok, but after reading the docs I do not believe I could. If someone could please help, I would greatly appreciate it.
Have the final request return a token, use that to check if it's the last request, if it is, hide the spinner
What happens if I don't know which one will finish last though? The service calls I am using are very slow and I don't control them. If I have 3 calls, the first one might be the only one with data in it, and it might take a while for it to finish, while the last 2 return no do and complete very quickly. Amazing response time as well, Thank you!
But you do know the amount of request_times within the loop, I assume - or else the loop will never end. So what you could do is you do a comparison of i == (request_times parseInt(-1)) and when it matches, end the spinner?
Create an array where you'll push all the ajax requests into. That way you'll be able to call your 'All done' code within $.when.apply().done(); var requestarray=[]; for (var i=0; i<requests_times; i++) { var request = $.ajax({ /* your call settings */ }) requestarray.push(request); } $.when.apply(null, requestarray).done(function(){ alert('All done'); })
The array thing seems needlessly complex -- I'd just have a counter. When you make a request, increment the counter and make sure the spinner is showing. When the request finishes decrement the counter and if it hits zero, remove the spinner. WAY simpler.