我正在尝试编写一个简单的Jquery AJAX轮询。我想确保请求不要备份'在浏览器中,如果Web服务器很慢(在我的特定情况下非常频繁......)。
这是我的代码:
(function poll() {
$.ajax({
url: CONFIG.apiBase,
type: 'GET',
data: { name: DESTINATIONS },
traditional: true,
success: updateDisplay,
error: getError,
complete: setTimeout(poll, 2000),
timeout: 10000,
});
})();
我认为这应该有效的方法是,如果请求成功,它将执行updateDisplay
然后等待2秒再开始另一个轮询请求。
但是,如果我的服务器速度太慢且无法在10秒内响应,那么将调用getError
,请求将被取消,最后它将等待2秒再尝试再次轮询
然而,实际发生的是浏览器每2秒轮询一次服务器,如果服务器速度慢,则会导致请求备份:
我是否从根本上误解了timeout
应该如何运作?
答案 0 :(得分:1)
问题在于您的setTimeout(poll, 2000)
行。目前它每2秒调用一次poll()
函数,因为您不等待先前的请求完成。要解决此问题,请将其包装在匿名函数中:
(function poll() {
$.ajax({
url: CONFIG.apiBase,
type: 'GET',
data: { name: DESTINATIONS },
traditional: true,
success: updateDisplay,
error: getError,
complete: function() {
setTimeout(poll, 2000)
},
timeout: 10000,
});
})();