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

标签 javascript jquery delay settimeout

我已经阅读了有关此问题的一些答案,但我不确定在我的情况下该怎么做。

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

问题出在我当前的设置中,我想调用 setTimeOut 来延迟函数的执行,但我认为因为我在另一个函数中,所以它不知道 startAjaxSubmitLoop() 函数的位置?但是,当我运行代码并 checkin 控制台时,我看到数百万个连接一个接一个地连接到我的服务器,没有任何延迟。 就好像 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');
                    });
                }

最佳答案

您错误地调用了 setTimeout。您将立即在 setTimout 行调用 startAjaxSubmitLoop 并将结果传递给 setTimeout 而不是您的函数。 Modern setTimeout implementations (es5)让您将参数传递给 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

关于javascript - 延迟执行脚本 Jquery(或 SetTimeOut),但超出范围时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20505462/

相关文章:

javascript - 拼接未按我预期的方式工作

jquery - 单独获取文本

javascript - 如何在 Spring MVC 4 和 jQuery I18N 中使用语言属性?

javascript - Angular HTTP 请求延迟拦截器未按预期工作

amazon-web-services - Amazon S3 中的日志延迟

javascript - jquery tablesorter 不适用于通过 ajax 获取的表,但适用于静态表

javascript - 从 php 传递编码变量并在 javascript 中解码?

PHP - sleep 错误()

javascript - 如何重新排序异步函数的执行顺序?

javascript - 如何解决DataTables表头列宽和表体列宽有时不匹配的问题?