我需要一些关于我正在编写的代码的帮助.. 我的代码触发三个异步请求并更新页面上的一些内容。 我希望每 X 秒触发一次这些请求.. 我见过几个这样的问题,how to schedule ajax calls every N seconds?关于setTimeout或setInterval,但问题是我需要每x秒触发每个请求..而我唯一能想到的setInterval/settimeout不会为每个调用计算单独的时间,而只是一次.. 例如
if i have xhr1 at 00.00.01 xhr2 at 00.00.02 and xhr3 at 00.00.03
下一次通话最好在每次 20 秒后进行?
xhr1 00.00.21 xhr2 00.00.22 xhr3 00.00.23
xhr1 00.00.41 xhr2 00.00.32 xhr3 00.00.33
我当前的代码也是这样编写的,即使用回调函数收到前一个响应后,每个 xhr 都会被触发
function request(url, callback){
....
asychronous request
....
callback(responseText);
}
request(url1, function(){
some code
}
request(url2, function(){
some code
}
request(url3, function(){
some code
}
如果这三个调用还建议使用另一种方法,我想知道..
最佳答案
由于这是一个复杂的场景,我建议您查看 promises 。这不是一个简单的概念,但它可以让您在链接需求和回调之间保持关注点的清晰分离。
如果没有 promise ,您将需要在回调中包含下一个 xhr 调用。
Promise 包含在 jQuery 或 Dojo 等 JavaScript 库中。
一个更简单的场景是忘记链接请求:
function allRequests(){
request(url1, function(){some code});
// url2 one second later
setTimeout(function(){request(url2, function(){some code});},1000);
// url3 one more second later
setTimeout(function(){request(url3, function(){some code});},2000);
}
// run the 3 requests every 20 seconds
setInterval(allRequests(),20000);
关于javascript - 每 x 秒多个 XmlHttpRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13574882/