[英]How to recursively call a function 1 second after an ajax request is done?
我有一个案例,我不想每秒调用一个方法。 相反,我想在完成ajax请求后1秒钟调用一个函数,而不管结果如何。
我试图使用$.delay()
函数,但它给了我一个错误
TypeError: $.delay is not a function
这是我的代码
$(function(){
function checkMessages(){
$.ajax({
type: 'GET',
url: icwsHandlerUrl,
data: {method: 'getMessages', jSON: true},
dataType: 'json',
cache: false,
timeout: 5000,
success: function(data) {
console.log(data); // for testing only but this should call a handler for the data
},
complete: function(){
$.delay(1000, function(){
checkMessages();
});
}
});
}
$(window).load(function(){
checkMessages();
});
});
注意:我使用的是jQuery 2.1.0版
$.delay
用于延迟存储在jQuery事件队列中的事件。 为此,您应该使用JavaScript自己的setTimeout
方法:
setTimeout(checkMessages, 1000);
尝试将所有这些链接起来:
$(function(){
function checkMessages(){
$.ajax({
type: 'GET',
url: icwsHandlerUrl,
data: {method: 'getMessages', jSON: true},
dataType: 'json',
cache: false,
timeout: 5000,
success: function(data) {
console.log(data); // for testing only but this should call a handler for the data
},
complete: function(){
$.delay(1000, function(){
checkMessages();
});
}
});
}
$(window).load(function(){
checkMessages();
});
});
进入这个:
var req = $.ajax({
type: 'GET',
url: icwsHandlerUrl,
data: {method: 'getMessages', jSON: true},
dataType: 'json',
cache: false,
timeout: 5000,
success: function(data) {
console.log(data); // for testing only but this should call a handler for the data
},
complete: function(){
$.delay(1000, function(){
checkMessages();
});
}
});
var nextTask = req.then(function(data){something});
nextTask.done(function(data){somethingelse});
上面的代码将等待完成下一个任务所需的一切。 试试看。
确保删除$.delay()
并将其放入req.then()
函数中。
这是.then()
说明https://api.jquery.com/deferred.then/
编辑:
$(window).load(function{
$.delay(1000, function(){
checkMessages();
});
});
并在这段代码之外放置检查消息。
之前的答案包含所有基本位,但这是一个完整的解决方案:
$(function(){
var checkMessagesTimeout;
function checkMessages(){
$.ajax({
type: 'GET',
url: icwsHandlerUrl,
data: {method: 'getMessages', jSON: true},
dataType: 'json',
cache: false,
timeout: 5000,
success: function(data) {
console.log(data); // for testing only but this should call a handler for the data
},
complete: function(){
checkMessagesTimeout = setTimeout(function(){
checkMessages();
}, 1000);
}
});
}
$(window).load(function(){
checkMessages();
});
});
此版本具有将超时引用存储到变量中的额外好处,因此如果需要,您可以通过调用clearTimeout(checkMessagesTimeout);
在下一次ajax调用之前中止超时clearTimeout(checkMessagesTimeout);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.