你好我想制作一个智能轮询功能,其中每4个空响应之后,间隔应加倍。但是如果间隔达到最大间隔,它应该只保持该值。应该为它编写什么函数。
这是从php代码获取响应的代码。
function updateChat() {
console.log("inside updatechat");
setInterval(function()
$.ajax({
//type: "POST",
url: "file.php",
//data: id,
//dataType: JSON,
success: function(response) {
var result = JSON.parse(response);
//console.log("Result is " +result);
for (var i in result) {
$(".message_box").append('<p class = "shout_msg">' + result[i] + '</p>');
$(".message_box").scrollTop($(".message_box")[0].scrollHeight);
}
}
}), interval);
}
我的民意调查功能是什么?
答案 0 :(得分:1)
setInterval
每隔一段时间间隔调用一次回调...你需要的是setTimeout
:
var INITIAL_INTERVAL = 500; // 0.5 sec
var MAX_INTERVAL = 120000; // two minutes
var interval = INITIAL_INTERVAL;
var pollingFunction = function() {
$.ajax({
//type: "POST",
url: "file.php",
//data: id,
//dataType: JSON,
success: function(response) {
var result = JSON.parse(response);
if (result.length == 0) { // or whatever condition to check return of empty result
// empty result - poll server at slower pace
interval *= 2;
if (interval > MAX_INTERVAL) {
interval = MAX_INTERVAL;
}
}
else {
// reset interval to initial quick value
interval = INITIAL_INTERVAL;
}
//console.log("Result is " +result);
for (var i in result) {
$(".message_box").append('<p class = "shout_msg">' + result[i] + '</p>');
$(".message_box").scrollTop($(".message_box")[0].scrollHeight);
}
// activate the pollingFunction again after 'interval' ms
// important - set the timeout again of the polling function
setTimeout(pollingFunction, interval);
}
})
}
// activate the polling function the first time after interval ms
// important - set the timeout once (or call the polling function once) from outer scope.
setTimeout(pollingFunction, interval);