XHR请求的setTimeout [英] setTimeout for XHR requests

查看:167
本文介绍了XHR请求的setTimeout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

引用 MDC

如果您的逻辑执行时间可能比间隔时间长,则建议您使用window.setTimeout递归调用命名函数。例如,如果使用setInterval每5秒轮询一次远程服务器,网络延迟,无响应的服务器以及许多其他问题可能会阻止请求在其分配的时间内完成。因此,您可能会发现自己排队的XHR请求不一定按顺序返回。

If there is a possibility that your logic could take longer to execute than the interval time, it is recommended that you recursively call a named function using window.setTimeout. For example, if using setInterval to poll a remote server every 5 seconds, network latency, an unresponsive server, and a host of other issues could prevent the request from completing in its alloted time. As such, you may find yourself with queued up XHR requests that won't necessarily return in order.

对于这种情况,首选递归setTimeout模式:

For such cases, a recursive setTimeout pattern is preferred:



(function loop(){
   setTimeout(function(){

      // logic here

      // recurse
      loop();

  }, 1000);
})();




在上面的代码片段中,声明了一个命名的函数循环并立即生效执行。在逻辑完成执行后,在setTimeout内递归调用循环。虽然这种模式不能保证在固定的时间间隔内执行,但它确保在递归之前完成了前一个时间间隔。

In the above snippet, a named function loop is declared and is immediately executed. loop is recursively called inside setTimeout after the logic has completed executing. While this pattern does not guarantee execution on a fixed interval, it does guarantee that the previous interval has completed before recursing.

我不知道了解这是如何解决问题的。我不应该从XHR回调中调用loop()而不是从setTimeout调用吗?

I don't understand how this fixes the problem. Shouldn't I call loop() from inside the XHR callback and not from setTimeout?

推荐答案

原始问题与 setInterval():在收到对第一个的回复之前,可能会发送两个或更多个AJAX请求(取决于网络延迟和计时器延迟)。如果发生这种情况,则无法保证按顺序调用它们各自的回调。

The original problem is related to setInterval(): it's possible for two or more AJAX requests to be sent before the reply to the first one is received (depending on the network latency and the timer delay). If that happens, their respective callbacks are not guaranteed to be called in order.

解决方案是使用 setTimeout()<单独延迟每个请求/ code>并且仅在当前请求返回后(即在该请求的回调中)安排下一个请求。

The solution is to delay each request independently with setTimeout() and only schedule the next request after the current request has returned (i.e. in that request's callback).

所以,你是绝对正确的:调用来自延迟函数本身的 setTimeout()(通过 loop())仅重新实现较差的的setInterval()。你确实必须从AJAX回调中调用 loop()来获得预期的行为。

So, you're absolutely right: calling setTimeout() (through loop()) from the delayed function itself only reimplements a poorer setInterval(). You indeed have to call loop() from the AJAX callback to obtain the expected behavior.

这篇关于XHR请求的setTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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