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

Javascript 延迟执行脚本Jquery(或SetTimeOut),但在超出范围时,javascript,jquery,delay,settimeout,Javascript,Jquery,Delay,Settimeout,我已经读了一些关于这个问题的答案,但我不知道我该怎么办 我有一个函数,其思想是它将继续尝试通过AJAX进行连接,如果失败,它将继续每5秒重试一次以提交信息。这对于我正在开发的一个web应用程序来说很重要,在这个应用程序中,用户50%的时间是离线的,50%的时间是在线的 问题是在我当前的设置中,我想调用setTimeOut来延迟函数的执行,但我认为因为我在另一个函数中,它不知道startAjaxSubmitLoop()函数的位置?但当我运行代码并签入控制台时,我看到数百万个连接毫不延迟地一个接一个

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

我有一个函数,其思想是它将继续尝试通过AJAX进行连接,如果失败,它将继续每5秒重试一次以提交信息。这对于我正在开发的一个web应用程序来说很重要,在这个应用程序中,用户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');
                    });
                }

您没有正确调用
setTimeout
。您正在
setTimout
行上立即调用您的
startAjaxSubmitLoop
,并将结果传递给
setTimeout
,而不是您的函数。您可以将参数传递给setTimeout,如下所示:

而不是:

setTimeout(startAjaxSubmitLoop(id,tech_id),5000);
使用:

要支持
setTimeout
不使用参数的旧浏览器,标准方法是只包装函数
startAjaxSubmitLoop

setTimeout(function(){startAjaxSubmitLoop(id, tech_id)}, 5000); //equivalent to above
有两种方法可以做到这一点:

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

2) 函数名(无括号)和超时时间后列出参数:
setTimeout(startAjaxSubmitLoop,5000,id,tech_id)

谢谢,很好!我不知道我做错了。谢谢。您的第三个示例缺少回调中的分号。它应该是
setTimeout(function(){startAjaxSubmitLoop(id,tech_id);},5000)使它看起来像是你复制了我的代码示例。@ps2goat我在你之前发布过,半自动插入。”
setTimeout(function(){startAjaxSubmitLoop(id, tech_id)}, 5000); //equivalent to above