我有这个结构中的代码。
如果错误状态为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); }
},
//...
});
}