2013-12-10 125 views
0

我已阅读关于此问题的一些答案,但我不知道在我的情况下做什么。延迟执行脚本jquery(或SetTimeOut)但超出范围

我有一个功能,它的想法是不断尝试通过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'); 
        }); 
       } 

回答

1

不正确地打电话给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犯规采取params为以标准方式只是包装你的功能startAjaxSubmitLoop

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

谢谢工作很好!我不知道我做错了。谢谢。 –

+0

您的第三个示例缺少回调中的分号。它应该是'setTimeout(function(){startAjaxSubmitLoop(id,tech_id);},5000);'看起来像你复制我的代码示例。 – ps2goat

+0

@ ps2goat我发布之前你和半自动插入 – megawac

1

两种方法:

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

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