i need some help on some code that i m writting.. my code fires three asychronous requests and updates some content on my page. i want these requests to be fired every X seconds.. i have seen several questions like this, how to schedule ajax calls every N seconds? regarding setTimeout or setInterval, but the issue is that i need each request to be fired every x seconds..while the only i can think of that setInterval / settimeout wouldn't count seperate time for each call, but just one time.. for instance
if i have xhr1 at 00.00.01 xhr2 at 00.00.02 and xhr3 at 00.00.03
what aproach would it be best for the next call to be after 20seconds for each?
xhr1 00.00.21 xhr2 00.00.22 xhr3 00.00.23
xhr1 00.00.41 xhr2 00.00.32 xhr3 00.00.33
also my current code is writen in that way that every xhr is fired after response of previous has been received using a callback function
function request(url, callback){
....
asychronous request
....
callback(responseText);
}
request(url1, function(){
some code
}
request(url2, function(){
some code
}
request(url3, function(){
some code
}
if another approach is suggested as well for the three calls, i would like to know..
Some options are:
Do all three requests at the exact same time. Is there a reason that all three requests cannot be done at the same time?
Or chain your requests using the success function of the previous request.
Or stagger your requests at the start with timeouts.
As this is an intricate scenario, I'd recommend that you look into promises. It's not an easy concept, but it'll allow you to keep a clear separation of concerns between your chaining needs and your callbacks.
Without promises, you would need to include the next xhr call in your callback.
Promises are included in JavaScript libraries like jQuery or Dojo.
A simpler scenario would be to forget about chaining the requests: