AceCorban
AceCorban

Reputation: 2103

Long Polling: How do I calm it down?

I'm working on a simple chat implementation in a function that has an ajax call that invokes a setTimeout to call itself on success. This runs every 30 seconds or so. This works fine, but I'd like a more immediate notification when a message has come. I'm seeing a lot of examples for long polling with jQuery code that looks something like this:

function poll()
{
    $.ajax(
    {
        data:{"foo":"bar"},
        url:"webservice.do",
        success:function(msg)
        {
           doSomething(msg);
        },
        complete:poll
    });
}

I understand how this works, but this will just keep repeatedly sending requests to the server immediately. Seems to me there needs to be some logic on the server that will hold off until something has changed, otherwise a response is immediately sent back, even if there is nothing new to report. Is this handled purely in javascript or am I missing something to be implemented server-side? If it is handled on the server, is pausing server execution really a good idea? In all of your experience, what is a better way of handling this? Is my setTimeout() method sufficient, maybe with just a smaller timeout?

I know about websockets, but as they are not widely supported yet, I'd like to stick to current-gen techniques.

Upvotes: 2

Views: 245

Answers (4)

Rob Schmuecker
Rob Schmuecker

Reputation: 8954

There is no proper way to handle this on the javascript side through traditional ajax polling as you will always have a lag at one end or the other if you are looking to throttle the amount of requests being made. Take a look at a nodeJS based solution or perhaps even look at the Ajax Push Engine www.ape-project.org which is PHP based.

Upvotes: 1

Plymouth223
Plymouth223

Reputation: 1925

You've identified the trade-off, open connections to the web server, therefore consuming http connections (i.e. the response must block server side) vs frequent 'is there anything new' requests therefore consuming bandwidth. WebSockets may be an option if your browser base can support them (most 'modern' browsers http://caniuse.com/websockets)

Upvotes: 1

Michael Lorton
Michael Lorton

Reputation: 44386

You missed the long part in "long polling". It is incumbent on the server to not return unless there's something interesting to say. See this article for more discussion.

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

Do no pause the sever execution... it will lead to drying out server resources if lot of people try to chat...

Use client side to manage the pause time as you did with the setTimeout but with lower delay

Upvotes: 2

Related Questions