The best way to fetch messages for chat window?


I have implemented a very basic chat window similar to Facebook for my website. What I am doing right now to fetch message is to use a “SetInterval” function to read messages from the MySql database every second and output everything to the chatwindow using html().

The problem with this method is that sometimes the database is slow to respond and different undesired behaviours can happen. E.g. the chat window draws a blank. Is there a better way of doing this? Caching the chat history on the client side maybe? How can I do that if caching is the way to go?

First of all, use setTimeout instead of setInterval. That will allow you to wait for each server response before sending next request. When using setInterval there is a possibility to receive older results after newer (because each request to server can take different amount of time but setInterval doesn’t care about that fact).

Then, before you put new html into the chat box check if that html isn’t empty. If response is empty, don’t replace anything (this is the caching you’re talking about). On the server side make sure you’re sending empty answer if something wrong with database right now.

You will come to something like this:

function refreshChat(){
    $.post('server.php', data, function(result){
        // when we get new chat html from the server
        // and it isn't empty replace it in the chat window
        if (result != '') { 
        // set timeout for next refresh only when previous is completed
        // that guarantee you will not receive older results later than newer
        setTimeout("refreshChat()", 1000);

// first timeout to start the process
setTimeout("refreshChat()", 1000);

Thanks @megazoid! It looks like a good design and not too convoluted to implement :smiley:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.