2010-05-06 34 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