我已閱讀關於此問題的一些答案,但我不知道在我的情況下做什麼。延遲執行腳本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');
});
}
謝謝工作很好!我不知道我做錯了。謝謝。 –
您的第三個示例缺少回調中的分號。它應該是'setTimeout(function(){startAjaxSubmitLoop(id,tech_id);},5000);'看起來像你複製我的代碼示例。 – ps2goat
@ ps2goat我發佈之前你和半自動插入 – megawac