gpt4 book ai didi

javascript - 智能轮询功能

转载 作者:行者123 更新时间:2023-12-03 11:33:35 27 4
gpt4 key购买 nike

您好,我想制作一个智能轮询功能,其中每 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);

}

我的投票功能是什么?

最佳答案

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);

关于javascript - 智能轮询功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26629486/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com