[英]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.