javascript Jquery/ajax 循环 SetTimeout
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23050077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery/ajax Looping SetTimeout
提问by Kim Oliveros
Hi I'm stuck on my setTimeout function. What i'm trying to do is to loop my setTimeout for my retrieve conversation function.. I have tried this on setInterval but using setInterval is a badnews for my application which is why I switch to setTimeout.. But I cant seem to figure out how to make the setTimeout work again after its done loading.. here is what I have tried so far and still trying to make it work at the moment..
嗨,我被我的 setTimeout 函数困住了。我想要做的是循环我的 setTimeout 以获取我的检索对话功能。如何在完成加载后使 setTimeout 再次工作..这是我迄今为止尝试过的并且目前仍在努力使其工作..
Javascript:
Javascript:
id = setTimeout(function()
{
$.ajax(
{
url: "includes/handlechat.php",
type: "GET",
data: data,
dataType: 'json',
success: function(result)
{
$("#clog").empty();
$.each(result, function(rowKey, row)
{
$("#clog")
.append('<p ><h4>'+ row.username +':</h4>' + row.message_content + '</p>' );
});
},
complete: function ()
{
clearTimeout(id);
}
})
}, 1101);
Any tips or suggestion ?
任何提示或建议?
回答by Felix Kling
Put the code in a function and call it in the success or complete handler:
将代码放在一个函数中并在成功或完成处理程序中调用它:
function load() {
setTimeout(function () {
$.ajax({
url: "includes/handlechat.php",
type: "GET",
data: data,
dataType: 'json',
success: function (result) {
$("#clog").empty();
$.each(result, function (rowKey, row) {
$("#clog").append('<p ><h4>' + row.username + ':</h4>' + row.message_content + '</p>');
});
},
complete: load
});
}, 1101);
}
load();
You can also use an IIFE to avoid creating another binding in the current environment:
您还可以使用 IIFE 来避免在当前环境中创建另一个绑定:
(function load() {
// setTimeout here
}());
回答by Paul
I'd do something like this.
我会做这样的事情。
function getChatMessages() {
$.ajax({
// your params here
}).done(function (data) {
// do something with the data
}).always(function () {
window.setTimeout(getChatMessages, 1101);
});
}
getChatMessages();
Purpose of the '.always' is so you don't get some error on fetching messages (timeout, some kind of 500, etc) that breaks your loop.
'.always' 的目的是让您在获取消息(超时、某种 500 等)时不会出现一些会中断循环的错误。