James T
James T

Reputation: 3320

Javascript ajax double request

I have a AJAX jQuery chat application, it works by asking for new messages, at the start it just asks for 20 most recent messages, then it gets the count of the latest message, so when it asks again, it knows what the last message ID was, and the server returns message since then.

The issue is on slower connections, it takes longer then the rate it requests, resulting in getting more then one of the same message because there are more then one request running with the same old message ID.

How would I make sure it only is running one request at a time?

Upvotes: 1

Views: 1141

Answers (3)

rcravens
rcravens

Reputation: 8390

What about a re-entrant function? Something like:

function getMessages(){
   $.get('url', function(data){
      //process the data

      getMessages();
   });
}

Upvotes: 0

lonesomeday
lonesomeday

Reputation: 237865

I presume you are using setInterval to do your repeated requests. This isn't best practice, for the exact reason you mention: if a function takes a long time, a new one may take place before the previous iteration had completed.

It is best to use setTimeout within the complete handler of your post call:

function doRequest() {
    $.ajax({
        url: 'someurl',
        /* some other options */
        complete: function(){
            setTimeout(doRequest, 30000);
        }
    });
}
doRequest();

Upvotes: 4

Quentin
Quentin

Reputation: 943561

Use a setTimeout in the onreadystatechange event handler (success and error in jQuery terms IIRC) to fire off the 'next' request. Don't use setInterval and send them out on a timer regardless.

Upvotes: 0

Related Questions