2013-12-10 104 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);