使用带有Ajax调用的SetTimeout

我试图使用setTimeout来检查表中是否存在数据:

如果数据存在则不获取数据。 如果数据不存在,则使用load获取数据,然后每x分钟执行相同的操作。

这是我到目前为止所拥有的。 出于某种原因,当它触及If块时, setTimeout不起作用。

我甚至不确定这是否是最好的方法。

  var sTimeOut = setTimeout(function () { $.ajax({ url: 'CheckIfDataExists/' + new Date().getTime(), success: function (response) { if (response == 'True') { $('.DataDiv') .load('GetFreshData/' + new Date() .getTime(), { "Id": $("#RowID").val() }); } }, complete: function () { clearTimeout(sTimeOut); } }); }, 10000); 

任何帮助将不胜感激。

更新 …

  setTimeout(function(){checkData()}, 5000); function checkData(){ $.ajax({ url: 'CheckIfDataExists/' + new Date().getTime(), success: function (response) { if (response == 'True') { $('.DataDiv') .load('GetFreshData/' + new Date() .getTime(), { "Id": $("#RowID").val() }); } else { $('.OutOfWindow').html('No Data Found'); setTimeout(function () { checkData() }, 5000); } }, complete: function () { // clearTimeout(sTimeOut); } }); } 

像这样的东西应该工作,第一个片段是本地化的,所以我可以测试运行它。 我已经解释了代码,下面是代码应该是什么

就像你意识到的那样(从post上的更新开始), setTimeout只调用你的目标函数一次 ,所以为了继续检查你需要再次调用它,如果你做了一个失败的检查。

在JsFiddle上看到它: http : //jsfiddle.net/jQxbK/

 //we store out timerIdhere var timeOutId = 0; //we define our function and STORE it in a var var ajaxFn = function () { $.ajax({ url: '/echo/html/', success: function (response) { if (response == 'True') {//YAYA clearTimeout(timeOutId);//stop the timeout } else {//Fail check? timeOutId = setTimeout(ajaxFn, 10000);//set the timeout again console.log("call");//check if this is running //you should see this on jsfiddle // since the response there is just an empty string } } }); } ajaxFn();//we CALL the function we stored //or you wanna wait 10 secs before your first call? //use THIS line instead timeOutId = setTimeout(ajaxFn, 10000); 

您的代码应如下所示:

 var timeOutId = 0; var ajaxFn = function () { $.ajax({ url: 'CheckIfDataExists/' + new Date().getTime(), success: function (response) { if (response == 'True') { $('.DataDiv'). load('GetFreshData/' + new Date(). getTime(), { "Id": $("#RowID").val() }); clearTimeout(timeOutId); } else { timeOutId = setTimeout(ajaxFn, 10000); console.log("call"); } } }); } ajaxFn(); //OR use BELOW line to wait 10 secs before first call timeOutId = setTimeout(ajaxFn, 10000);