views:

85

answers:

2

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.
}
+1  A: 

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

choise
Or generally the technique known as COMET: http://en.wikipedia.org/wiki/Comet_%28programming%29
RoToRa
+1  A: 

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.)

Quotidian