开发者

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?

开发者_StackOverflow中文版
// 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.
}


Check out CometD. It's a js long-polling system I've used with some success for simple chat systems integrated with jQuery. (Last time I looked, there were a few jQuery specific implemetations, but I never found one that was robust enough for me.)


you can checkout this push engine so that you have not to poll for new data anymore. check it out, its really cool.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜