引用 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/