繁体   English   中英

聊天应用程序轮询

[英]Chat application polling

我正在开发一个聊天应用程序,它会在超时时轮询服务器。 如果随着时间的推移,没有任何近期活动,则超时会增加。 函数loadNew()对服务器执行ajax调用,服务器响应消息数据。

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

我遇到的问题是超时功能不等待函数loadNew()完成,这导致相同的轮询发送两次或更多,如果超时低于ajax调用所需的时间功能完成。 因此,服务器多次响应相同的数据,这导致在聊天中重复显示消息。

有没有办法在loadNew()完成获取和显示数据后才触发超时?

编辑:使用@Brad M的答案后,它不再重复消息了。 在用户提交消息后,我仍然希望有一种方法可以调用轮询,因此会立即显示新消息。 这会干扰loadNew()设置的超时,这会导致消息再次重复。 你能想出一种方法来实现这个目标吗?

使用ajax回调函数(如successcomplete来触发新的轮询。

如果没有看到你的loadNew函数,一个简单的修复可能是更改该函数以返回你的ajax调用( return $.ajax({...}); )并将你发布的代码更改为:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM