Jquery/ajax循环设置超时
Jquery/ajax Looping SetTimeout
嗨,我的setTimeout函数被卡住了。我想做的是为我的检索会话函数循环我的setTimeout。。我在setInterval上尝试过,但使用setInterval对我的应用程序来说是个坏消息,这就是我切换到setTimeout的原因。。但是我似乎不知道如何让setTimeout在加载完成后再次工作。。以下是我迄今为止所做的尝试,目前仍在努力使其发挥作用。。
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);
有什么建议吗?
将代码放入函数中,并在成功或完成处理程序中调用它:
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();
您还可以使用IIFE来避免在当前环境中创建另一个绑定:
(function load() {
// setTimeout here
}());
我会做这样的事情。
function getChatMessages() {
$.ajax({
// your params here
}).done(function (data) {
// do something with the data
}).always(function () {
window.setTimeout(getChatMessages, 1101);
});
}
getChatMessages();
".总是"的目的是为了避免在获取消息时出现一些错误(超时、某种500等),从而中断循环。
$.ajax({
url: "includes/handlechat.php",
type: "GET",
data: data,
dataType: 'json',
success:function(data){
//your succesfull code
},
error:function(){
//code when time is out
},
timeout:10000 // will return the code in error after 10 seconds
});
相关文章:
- 为什么页面重新加载会使设置超时无效,以及如何避免
- 立即设置超时
- iOS Safari Javascript设置超时问题
- 如何将嵌套设置超时转换为承诺
- 如何循环设置超时函数
- 关于设置超时/间隔上下文
- 清除设置超时之前的间隔将不起作用
- 在悬停功能中设置超时
- 延迟设置超时()
- 我们是否需要设置超时进行短轮询
- 更合乎逻辑的设置超时例程
- 应设置超时触发多少次
- 如何获得设置超时以从输入中读取值
- 尝试为函数和passvariable设置超时-dos'不起作用
- 清除超时多次设置超时
- Javascript设置超时和重定向-IE冻结
- 当一些文本粘贴到文本框中时(没有设置超时),是否检查数字
- 重置设置超时-javascript
- 间隔/设置超时起点
- 设置超时难度