2010-05-06 35 views
0

由于某种原因,这个检查新的聊天消息会导致浏览器的数量(以及某种程度上的服务器)的负载超出我的预期。任何人都可以看到我可以提高效率的方法来减轻负载?如何让我的JavaScript聊天轮询脚本更高效?

// 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

var secs = 1; :o) – jAndy 2010-05-06 13:06:30

+0

没错。 :我想我应该指出这是问题的一部分。我很乐意提供更快的检查时间来更频繁地更新聊天记录,但它似乎使浏览器紧缩得有点过分。 (并且我承担了对服务器负载的影响,尽管我本身无法衡量) – Kzqai 2010-05-06 15:05:53

回答

1

结帐CometD。这是一个js的长轮询系统,我用了jQuery的简单聊天系统取得了一些成功。 (上次我看,有几个jQuery特定的实现,但我从来没有发现一个足够强大的我。)

+0

你不会碰巧有使用CometD的公共代码,你会...... – Kzqai 2011-03-08 23:37:30

1

您可以结帐this push engine,这样您就不必再为新数据轮询。 检查出来,它真的很酷。

+0

或者通常称为COMET的技术:http://en.wikipedia.org/wiki/Comet_%28programming% 29 – RoToRa 2010-05-06 13:18:06