I'm working on a chat application, which polls the server at a timeout. The timeout increases if, over time, there hasn't been any recent activity. The function loadNew()
performs an ajax call to the server, which responds with message data.
pollTimeoutTime = 500;
function poll() {
pollTimeout = setTimeout(function(){
loadNew();
if (!new_messages_count) {
//Increasing delay between polls as no messages are incoming to a maximum of 1 minute/60 seconds
if (pollTimeoutTime < 60000) pollTimeoutTime = pollTimeoutTime * 1.25;
}
else {
//Reset delay between poll to default of 0.5 seconds
pollTimeoutTime = 500;
}
poll();
},pollTimeoutTime);
}
The problem I'm having is that the timeout function does not wait for the function loadNew()
to complete, which causes the same poll to be sent twice or more if the timeout is lower than the time it takes for the ajax call in the function to complete. The server thus responds with the same data multiple times, which leads to duplicative display of messages in the chat.
Is there a way to make the timeout only trigger after loadNew()
has finished fetching and displaying the data?
EDIT: after using @Brad M's answer, it doesn't duplicate messages anymore. I would still like to have a way to call for a poll after the user submits a message, so the new message is displayed immediately. This would interfere with the timeout set in loadNew()
, which would cause messages to be duplicated again. Could you think of a way to get that working?
使用ajax回调函数(如success
或complete
来触发新的轮询。
Without seeing your loadNew
function, an easy fix might be to change that function to return your ajax call ( return $.ajax({...});
) and change the code you posted to this:
pollTimeoutTime = 500;
function poll() {
pollTimeout = setTimeout(function () {
loadNew().done(function (result) {
if (!new_messages_count) {
//Increasing delay between polls as no messages are incoming to a maximum of 1 minute/60 seconds
if (pollTimeoutTime < 60000) pollTimeoutTime = pollTimeoutTime * 1.25;
} else {
//Reset delay between poll to default of 0.5 seconds
pollTimeoutTime = 500;
}
poll();
});
}, pollTimeoutTime);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.