代码之家  ›  专栏  ›  技术社区  ›  Kzqai

如何使javascript聊天轮询脚本更高效?

  •  0
  • Kzqai  · 技术社区  · 16 年前

    出于某种原因,这种对新聊天信息的检查会导致比我预期的更多的浏览器(在某种程度上是服务器)负载。有人知道我有什么办法能让它更有效,减轻负担吗?

    // 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.
    }
    
    2 回复  |  直到 16 年前
        1
  •  1
  •   Quotidian    16 年前

    退房 CometD . 这是一个js长轮询系统,我已经成功地将它用于与jQuery集成的简单聊天系统(上次我查看时,有一些特定于jQuery的实现,但我从来没有找到一个对我来说足够强大的实现。)

        2
  •  1
  •   choise    16 年前

    this push engine 这样你就不用再为新数据投票了。

    推荐文章