我有一个jQuery .ajax调用的以下部分。它每秒都会检查我相信。如何在10次尝试后停止?
success: function (data) {
if (!data) {
setTimeout(function (inputInner) { CallIsDataReady(inputInner); }, 1000);
}
编辑:我实施了一个解决方案,但服务调用的日志记录似乎在2次后停止。
function CallIsDataReady(input) {
var timer;
var count = 0;
$.ajax({
url: "http://www.example.com/services/TestsService.svc/IsDataReady",
type: "GET",
contentType: "application/json; charset=utf-8",
data: input,
// dataType: "json",
success: function (data) {
if (!data) {
setTimeout(function(inputInner) {
CallIsDataReady(inputInner);
count++;
if (count == 10) {
clearInterval(timer);
count = 0;
}
}, 1000);
}
else {
console.log("data returned - calling callUpDateGrid");
//Continue as data is ready
callUpdateGrid(input);
}
},
error: function (jqXHR, textStatus, errThrown) {
console.log("AJAX call failed in CallIsDataReady");
console.log(errThrown);
}
});
答案 0 :(得分:1)
只需将setTimeout分配给变量,并使用计数器,当它达到10时,调用clearTimeout()
答案 1 :(得分:1)
if (!data) {
var count = 0;
var interval;
interval = setInterval(function (inputInner) {
if (count === 10) {
clearInterval(interval);
return;
}
CallIsDataReady(inputInner);
count++;
}, 1000);
}
答案 2 :(得分:0)
// global variable - should be outside your ajax function
var timer;
var count = 0;
....
success : function( data) {
if( ! data ) {
// don't know where you are getting inputInner. assuming its a global variable
timer = setInterval ( function ( inputInner ) {
CallIsDataReady(inputInner);
count++;
if ( count == 10 ) {
clearInterval(timer);
count = 0;
}
}, 1000);
}
}
答案 3 :(得分:0)
使用间隔
var count = 0,
handler = setInterval(dostuff, 1000);
function dostuff(inputInner){
//CallIsDataReady(inputInner);
if(++count === 10)
clearInterval(handler);
}
但是,你永远不应该依赖于ajax调用总是需要< 1000毫秒。检查XHR上的readyState
并确保它再次轮询之前为4。