javascript - 将 SetTimeout 与 Ajax 调用结合使用

标签 javascript asp.net-mvc-3 jquery

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

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

这是我目前所拥有的。出于某种原因,setTimeout 在遇到 If block 时不起作用。

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

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

最佳答案

这样的事情应该可行,第一个代码段已本地化,因此我可以测试运行它。我已经解释了代码,下面是您的代码应该是什么

正如您意识到的(从您的帖子更新中)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);

关于javascript - 将 SetTimeout 与 Ajax 调用结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9350746/

相关文章:

c# - Devexpress 12.1 MVC GridView 内部选项卡条问题

javascript - 在javascript中获取超链接的值

jquery - Jquery .not 的反义词是什么 - OR - 如何定位包含以下内容的 href 链接

javascript - 如何为动态网站编写用户脚本

c# - Entity Framework 、软删除和查询

asp.net-mvc - MVC 模型绑定(bind)到列表 - 丢失项目

jquery - 为什么我的图标在图像上的 "src"属性之后没有改变?

JavaScript/React/Node : Writing values to an existing excel file with condition

javascript - Node 如何将文件传递给 http.write 方法?

javascript - THREE.JS GLTFLoader,使用工作灯加载 blender 场景