简体   繁体   English

如何使我的javascript聊天轮询脚本更有效?

[英]How can I make my javascript chat polling script be more efficient?

For some reason this check for new chat messages causes a larger amount of browser (and to some extent server) load than I would expect. 由于某种原因,这种对新聊天消息的检查会导致比我预期的浏览器(在某种程度上是服务器)负载更多。 Anyone see any ways that I can make it more efficient, to lessen the load? 有人看到我有什么办法可以提高效率,减轻负担吗?

// Begin the cycle of refreshing the mini chat after the standard delay.
function startRefreshingMinichat(){
    var secs = 30; // Chat checking frequency.
    setTimeout(function (){
        checkForNewChats();
        startRefreshingMinichat(); // Loop the check for refresh.
    }, secs*1000);
}

// Check for the latest chat and update if it's different.
function checkForNewChats(){
    // Check whether the latest chat doesn't match the latest displayed chat.
    // NOTE THAT THIS CALLBACK DOES NOT TRIGGER IMMEDIATELY.
    $.getJSON('api.php?type=latest_chat_id&jsoncallback=?', function(data){
        var newChats = false;
        // Update global data stores if an update is needed.
        if(updateDataStore(data.latest_chat_id, 'chat_id', 'latestChatId', 'chat_id')){
            newChats = true;
        }
        if(newChats){ // there are new chats to show.
            refreshMinichat(null, 50); // loads new chat content.
        }
        // Since this callback isn't immediate, any feedback has to occur whenever the callback finishes.
 }); // End of getJSON function call.
}

you can checkout this push engine so that you have not to poll for new data anymore. 您可以检出此推送引擎,这样就不必轮询新数据了。 check it out, its really cool. 检查一下,它真的很酷。

Check out CometD . 看看CometD It's a js long-polling system I've used with some success for simple chat systems integrated with jQuery. 这是我已经成功用于与jQuery集成的简单聊天系统的js长轮询系统。 (Last time I looked, there were a few jQuery specific implemetations, but I never found one that was robust enough for me.) (上次查看时,有一些特定于jQuery的实现,但我从未发现有一个对我来说足够强大的实现。)

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

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