如何在n秒后重试AJAX循环n次

  • 本文关键字:AJAX 循环 重试 jquery ajax
  • 更新时间 :
  • 英文 :


我有这个结构中的代码。

如果错误状态为429,我希望在3秒钟后重试,最多重试3次。

$.ajax({
url : 'url',
type : 'PUT',
data :  'data',   
tryCount : 0,
retryLimit : 3,
success : function() {
// do something
},
error : function(response, status, error ) {
if (response.status == 429) {
this.tryCount++;
if (this.tryCount <= this.retryLimit) {
$.ajax(this);
return;
} else {
console.log('update failed!'); 
}
} else {
// handle other errors
}
}

});

我在哪里添加超时?我不断地循环。

您只需要用setTimeout包装器替换$.ajax(this)

$.ajax({
url: 'https://httpstat.us/429?sleep=500',
data: 'data',
tryCount: 0,
retryLimit: 3,
success: function() {
// do something
},
error: function(response, status, error) {
if (response.status == 429) {
this.tryCount++;
if (this.tryCount <= this.retryLimit) {
console.log('failure');
setTimeout(() => {
console.log('retrying');
$.ajax(this);
}, 3000);
return;
} else {
console.log('update failed!');
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

您是否考虑过将$.ajax放入函数中?

添加一个计数器变量和一个setTimeout就可以了。

counter = 0 ;
function ajaxfun () {
$.ajax({
//....
error : function(response, status, error ) {
counter ++;
if ( counter < 3) { setTimeout(function(){ ajaxfun(); }, 3000); }
},
//...
});
}

最新更新