延迟执行脚本Jquery(或SetTimeOut)但超出范围时

时间:2013-12-10 21:19:33

标签: javascript jquery delay settimeout

我已经阅读了一些关于这个问题的答案,但我不知道该怎么办。

我有一个功能,它的想法是它将继续尝试通过AJAX连接,如果它失败,它将继续每5秒钟再次尝试提交信息。这对于我正在开发的网络应用程序非常重要,用户在50%的时间处于离线状态,50%的时间处于在线状态。

问题出在我当前的设置中,我想调用setTimeOut来延迟函数的执行,但我认为因为我在另一个函数内部,它不知道startAjaxSubmitLoop()函数的位置?但是,当我运行我的代码并检查控制台时,我看到数百万个连接到我的服务器一个接一个没有延迟。 就好像setTimeout()函数延迟属性根本不起作用但它仍在运行函数?

任何想法我做错了什么?

function startAjaxSubmitLoop(id,tech_id){
                    //TODO: Make POST instead of GET because of pictures.
                    var request = $.ajax({
                      url: "script.php",
                      type: "GET",
                      data: { }
                    });

                    //If Successfully Sent & Got Response.
                    request.done(function( msg ) {
                        //Sometimes because of weak connections response may send, but the message it worked might not come back.
                        //Keep sending until for sure SUCCESS message from server comes back.
                        //TODO: Make sure server edits existing entries incase of double sends.  This is good in case they decide to edit anyways.
                      $( "#log" ).html( msg );
                    });

                    //If Failed...
                    request.fail(function( jqXHR, textStatus ) {
                        //Color the window the errorColor
                        //alert( "Request failed: " + textStatus );
                        setTimeout(startAjaxSubmitLoop(id,tech_id),5000);
                        console.log('test');
                    });
                }

2 个答案:

答案 0 :(得分:1)

您正在正确调用setTimeout。您正在startAjaxSubmitLoop行上立即呼叫setTimout并将结果传递给setTimeout而不是您的功能。 Modern setTimeout implementations (es5)允许您将args传递给setTimeout,如下所示:

而不是:

setTimeout(startAjaxSubmitLoop(id,tech_id),5000);

使用:

setTimeout(startAjaxSubmitLoop, 5000, id, tech_id); //call startAjaxSubmitLoop in 5000ms with id and tech_id

这样做的标准方法是支持setTimeout不接受参数的旧浏览器,只需将函数包裹startAjaxSubmitLoop

setTimeout(function(){startAjaxSubmitLoop(id, tech_id)}, 5000); //equivalent to above

答案 1 :(得分:1)

两种方法:

1)带回调函数:     setTimeout(function(){startAjaxSubmitLoop(id,tech_id);},5000);

2)在函数名称(无括号)和超时期限后列出参数:     setTimeout(startAjaxSubmitLoop,5000,id,tech_id);

相关问题