每 x 秒多个 XmlHttpRequests [英] Multiple XmlHttpRequests every x seconds

查看:51
本文介绍了每 x 秒多个 XmlHttpRequests的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些关于我正在编写的代码的帮助..我的代码触发三个异步请求并更新我页面上的一些内容.我希望每 X 秒触发一次这些请求..我见过几个这样的问题,如何每 N 秒安排一次 ajax 调用? 关于 setTimeout 或 setInterval,但问题是我需要每 x 秒触发每个请求..而我唯一能想到的 setInterval/settimeout 不会计算每个调用的单独时间,但只是一度..例如

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

如果我有 xhr1 在 00.00.01 xhr2 在 00.00.02 和 xhr3 在 00.00.03

if i have xhr1 at 00.00.01 xhr2 at 00.00.02 and xhr3 at 00.00.03

在每次 20 秒后进行下一次调用的最佳方法是什么?

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.21 xhr2 00.00.22 xhr3 00.00.23

xhr1 00.00.41 xhr2 00.00.32 xhr3 00.00.33

xhr1 00.00.41 xhr2 00.00.32 xhr3 00.00.33

我当前的代码也是这样编写的,在使用回调函数接收到前一个响应后,每个 xhr 都会被触发

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..

推荐答案

由于这是一个复杂的场景,我建议您查看 promises.这不是一个简单的概念,但它可以让您在链接需求和回调之间保持清晰的关注点.

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.

如果没有 promise,您需要在回调中包含下一个 xhr 调用.

Without promises, you would need to include the next xhr call in your callback.

Promise 包含在 JavaScript 库中,例如 jQuery 或 Dojo.

Promises are included in JavaScript libraries like jQuery or Dojo.

一个更简单的场景是忘记链接请求:

A simpler scenario would be to forget about chaining the requests:

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);

这篇关于每 x 秒多个 XmlHttpRequests的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆