使用SetTimeout与Ajax调用

11

我正在尝试使用 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); 
            } 
        }); 
    }

你有没有检查你的调试器来看看出了什么问题?这个JS看起来完全没问题:http://jsfiddle.net/FgT22/ - gideon
是的。它运行良好。当数据库中没有数据时(即响应为true)时,它按预期工作。当它为false时,我想在x分钟后重新检查。这就是问题所在。它不会重新检查。我清除超时成功的想法是下一次检查在前一个加载完成之前不应该被触发。 - mkizito76
这是我现在拥有的,它似乎可以工作。这是做这件事的最好方式吗?顺便说一句,感谢您的帮助。 - mkizito76
看看我的解决方案是否适用于你。 - gideon
1个回答

27

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

正如你在帖子更新中意识到的那样,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);

哇,太棒了!非常感谢您的帮助。还有一件事,当加载事件触发时,ajaxFn会立即执行。我想在ajaxFn执行之前等待一段时间(比如10秒),因为加载可能需要一些时间。换句话说,我想在执行ajaxFn之前等待10秒钟。这可行吗? - mkizito76
@user1219415 你的意思是在第一次调用之前要等待10秒钟吗?我已经更新了答案。 - gideon
很想帮忙,但我是新来的,所以做不到 :-(。 - mkizito76
点赞表示答案对某些人很有用,接受答案则表明它对你有效。这两件事都会给我一些美味的积分。查看接受答案的方式 - gideon
@user1219415 哈哈,是的,我忘了那件事!不管怎样,不客气,祝你有美好的一天 :) - gideon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接