所以我正在轮询一些非常标准的
(function poll(){
$.ajax({ ... })
});
而且效果很好。但现在,我希望能够继续每隔几秒钟进行一次轮询,如果两分钟后没有得到响应,就停止轮询并引发错误。
我该如何超时?
这样的东西怎么样。在ajax承诺中初始化、跟踪和重置轮询。
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();