简体   繁体   English

使用带有Ajax调用的SetTimeout

[英]using SetTimeout with Ajax calls

I am trying to use setTimeout to check if data exists in a table: 我试图使用setTimeout来检查表中是否存在数据:

If the data exists don't fetch data. 如果数据存在则不获取数据。 If the data des not exist fetch the data using load and then do the same thing every x minutes. 如果数据不存在,则使用load获取数据,然后每隔x分钟执行相同的操作。

Here is what I have so far. 这是我到目前为止所拥有的。 For some reason, the setTimeout does not work when it hits the If block. 由于某种原因,当它触及If块时, setTimeout不起作用。

I am not even sure if this is the best way to do this. 我甚至不确定这是否是最好的方法。

    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);

Any help will be greatly appreciated. 任何帮助将不胜感激。

Updated ... 更新 ...

    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); 
            } 
        }); 
    }

Something like this should work, the first snippet is localized so I could test run it. 这样的东西应该工作,第一个片段是本地化的,所以我可以测试运行它。 I've explained the code and below it is what your code should be 我已经解释了代码,下面是代码应该是什么

Like you realized (from your update on your post) setTimeout only calls your target function once , so to keep checking you need to call it again if you do a check that fails. 就像你意识到的那样(从帖子上的更新开始), setTimeout只调用你的目标函数一次 ,所以要继续检查你需要再次调用它,如果你做了一个失败的检查。

See it on JsFiddle : http://jsfiddle.net/jQxbK/ 在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);

Your code should look like this : 您的代码应如下所示:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM