我已阅读关于此问题的一些答案,但我不知道在我的情况下做什么。延迟执行脚本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