2014-09-24 69 views
0

所以我投票的东西非常标准如何停止由于超时而导致的轮询?

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

...它工作得很好。但是现在,我希望能够每隔几秒钟继续轮询,如果两分钟后没有得到回应,请停止轮询并提出错误。

我该如何做超时?

+0

首先想到的是在高温范围的一定程度的每次登录轮询当前时间('新的Date()')。然后检查以前存储的时间之间的差异,然后再作出决定 – ne1410s 2014-09-24 19:25:27

+0

您可能会感兴趣http://stackoverflow.com/questions/3543683/determine-if-ajax-error-is-a-timeout它解释如何检查超时错误的ajax响应。只需在.success上安排一个新的投票,然后在.error中检查是否超时错误 - 如果是,那么你去。 – 2014-09-24 19:26:06

回答

1

这样的事情如何?初始化,跟踪并重置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(); 
+0

这不会只是每个请求超时?我希望整个轮询过程在两分钟后结束。我可能会读这个错误... timeoutTimestamp给我一点点。 – 2014-09-24 20:22:14

+0

您要求它每隔几秒继续轮询一次。如果您在连续2分钟的投票请求中没有得到任何超时,投票将停止。 “always”承诺中的“setTimeout”会将每个响应的下一个轮询事件排队,直到2分钟的超时错误。 – deefour 2014-09-24 20:54:41

+0

为了清楚起见,我更改了'timeoutTimestamp'的名称。它的职责是存储可能是一系列超时响应的第一个时间戳。如果收到除“超时”之外的任何响应,则清除“firstTimeoutResponse”。 – deefour 2014-09-24 20:56:34

相关问题