gpt4 book ai didi

javascript - 如何因超时而停止轮询?

转载 作者:行者123 更新时间:2023-12-03 11:46:33 25 4
gpt4 key购买 nike

所以我正在投票一些非常标准的东西

(function poll(){
$.ajax({ ... })
});

...效果很好。但现在,我希望能够继续每隔几秒轮询一次,如果两分钟后没有得到响应,则停止轮询并引发错误。

如何实现超时?

最佳答案

这样的事情怎么样?在 ajax promise 内初始化、跟踪和重置轮询。

var pollingTimer     = null, // stores reference to the current timer id
firstTimeoutResponse = null; // stores the start of what might be a series of timeout responses

function poll(){
$.ajax({
// your options here...
}).done(function() {
// reset the "timeout" timer
firstTimeoutResponse = null;
}).fail(function(jqXHR, textStatus) {
// if the failure wasn't a timeout, short-circuit,
// but only after resetting the timeout timestamp
if (textStatus !== 'timeout') {
firstTimeoutResponse = null;

return;
}

// if it was a timeout failure, and the first one (!), init the timeout count
if (firstTimeoutResponse = null) {
firstTimeoutResponse = (new Date).getTime();
}
}).always(function() {
// if 2 min have passed and we haven't gotten a good response, stop polling/chort-circuit
if ((new Date).getTime() - firstTimeoutResponse > 120000) { // 120000ms = 2min
window.clearTimeout(pollingTimer);

return;
}

// queue the next ajax call
pollingTimer = window.setTimeout(poll, 3000); // poll every 3s
});
}

// kick things off!
poll();

关于javascript - 如何因超时而停止轮询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26024809/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com