Hi there,
I've knocked together a simple chatroom app that gets new messages via an ajax call and prepends it to the list of messages. It does this by looking for the first hidden div with ID comment_counter, which contains the ID of the most recent message in the list that the client already has. The ajax call then makes a request to another page that returns a string of HTML with just the messages with an ID greater than the most recent one. That gets prepended to the current list of messages, the interval repeats, and so on.
The function looks like this:
- setInterval(function()
- {
- var messageID = $("#comment_counter").first().html();
-
- $.get("page.php", { m: messageID, b: <?=($post_id)?>, n: 'true' },
- function(data) {
- if (data.length > 0)
- {
- $("#content").prepend(data);
- }
- else
- {
- if ($("#content").html().length == 0)
- {
- $("#content").html('<div class="comment_container"><div class="header"></div><div class="row">No comments yet</div></div>');
- }
- }
- }
- )
- return false;
- }, 5000);
Now this *works*, but the problem I'm seeing is that when the server is under heavy load, or the user's internet connection is being particularly slow, they will see multiple copies of new messages in the list. My theory is that by the time the asynchronous call to get new data has actually returned (under heavy load or slow conditions), the interval has elapsed and made another request for the same data (i.e. it looks for the first comment_counter value in the DOM, having not prepended data it's already requested, and multiple comments appear when that does eventually return).
I figure there are two ways to solve this. Firstly, I could just change setInterval to be a long time. Like a minute. If your web connection is being that slow to get a relatively small amount of data, you have bigger problems...
The problem with this is that it kinda negates the 'chat' aspect of the app if you're sitting there waiting a minute between messages. I know people could use MSN or some other instant message technology, but that's not quite the point... :-)
Secondly, I thought I could change the ajax get to be synchronous, but that locks up the user's browser and makes the whole thing unusable. Again, it kinda solves my problem, but with unacceptable side effects.
So, any suggestions? I haven't done any jQuery development prior to this, and it's been a while since a I did any web development anyway, so please be gentle! It's entirely possible I'm missing something very obvious, so any help much appreciated.
Cheers,
Tom