问题描述
我有一个案例,我不想每秒调用一个方法。 相反,我想在完成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版
1楼
$.delay
用于延迟存储在jQuery事件队列中的事件。
为此,您应该使用JavaScript自己的setTimeout
方法:
setTimeout(checkMessages, 1000);
2楼
尝试将所有这些链接起来:
$(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()
说明
编辑:
$(window).load(function{
$.delay(1000, function(){
checkMessages();
});
});
并在这段代码之外放置检查消息。
3楼
之前的答案包含所有基本位,但这是一个完整的解决方案:
$(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);