Question

I'm working on an application which implements longpolling because I want the user to receive notifications as soon as they arrive. I have this part working, but I also need to extend this with a javascript function which sends a 'heartbeat' to the server every 20 seconds.

My question: how do I do this without completely interrupting the code for 20 seconds (so that other javascript is still executed while it's counting) and is there some way to use a second connection for this? Because I don't want my longpolling to be interrupted when the heartbeat is sent to the user.

Any ideas?

Was it helpful?

Solution

You don't need to maintain multiple connections for what you're trying to achieve. Javascript's asynchronous nature allows the connection to stay alive while other things are being processed. You may have thought that javascript's XHR's were blocking because it is single threaded.

The XHR's in javascript are non-blocking because of the event loop model - the javascript engines are constantly in a loop, checking to see whether registered calls have completed and whether its callbacks should be processed. This allows its operations to be non-blocking and thus allowing a single javascript application to process multiple XHR long polling requests.

If you are able to use jQuery for the request, it wraps the XHR quite nicely with this function: http://api.jquery.com/jQuery.ajax/. With this, you can define a timeout of 20 seconds and handle it immediately (to reinitiate the connection with your server).

Aside - You may wish to consider your server stack to optimize long polling. Make sure that your web server does not spawn a thread per request (like Apache 2.2) - otherwise you will quickly run out of system resources! If you can use node.js (which is great for handling many simultaneous requests), look into socket.io library as a server-side and client-side solution (http://socket.io/#home).

OTHER TIPS

While the thread below is quite old, it shows that browsers allow multiple connections via XMLHttpRequest at any one time.

How many concurrent AJAX (XmlHttpRequest) requests are allowed in popular browsers?

If you have a long polling session either using an XMLHttpRequest or any other means of implementing comet, you can still create another request to the same server as part of a setInterval or setTimeout function until you reach the finite limit imposed by the browser, all that you would need to ensure is that you include the asynchronous flag in the construction of the XHR:

var heartbeatXhr = new XMLHttpRequest();
heartbeatXhr.open('GET', '/polling-url', true); // true for asynchronous

Use setInterval(yourHearbeatFunction, 20000), it doesn't lock Javascript execution thread. So, longpolled request will be processed as soon as it comes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top