javascript - XHR 请求的 setTimeout

标签 javascript settimeout

引用 MDC :

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.

For such cases, a recursive setTimeout pattern is preferred:

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

      // logic here

      // recurse
      loop();

  }, 1000);
})();

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 回调内部而不是从 setTimeout 调用 loop() 吗?

最佳答案

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

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

所以,您完全正确:从延迟函数本身调用 setTimeout()(通过 loop())只会重新实现较差的 setInterval() 。您确实必须从 AJAX 回调中调用 loop() 以获得预期的行为。

关于javascript - XHR 请求的 setTimeout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6888409/

相关文章:

javascript - 方法在本地运行良好,部署时不会运行(在meteor.com上)

javascript - 当遇到句点或逗号时,如何减慢从数组中输入随机字符串的函数?

jquery 悬停和 setTimeout/clearTimeOut

javascript - 我怎样才能让我的页面只刷新一次?

javascript - (JavaScript 和 HTML)单击时更改按钮的不透明度

javascript - 我如何优化这个调用 setTimeout() 的递归函数

javascript - Angularjs promise 未在 Controller 中解决

javascript - 如何更改 Angular Material 日期选择器当前日期颜色

python - 尽管超时,urllib2.urlopen 将永远挂起

javascript - 延迟循环 1 秒