How can I check for live updates without using setInterval/timeout? How can I check for live updates without using setInterval/timeout? ajax ajax

How can I check for live updates without using setInterval/timeout?


You should use websockets. You can connect to the server and register onmessage handler. Whenever the server has anything to be send to client, your handler will get invoked. No timeout needed.

Check for websocket support in your browser. As of now, only Chrome, Opera and Safari support them.

if ('WebSocket' in window){   /* WebSocket is supported. You can proceed with your code*/} else {   /*WebSockets are not supported. Try a fallback method like long-polling etc*/}

Connecting

var connection = new WebSocket('ws://example.org:12345/myapp');

Handlers

connection.onopen = function(){   console.log('Connection open!');}connection.onclose = function(){   console.log('Connection closed');}connection.onmessage = function(e){   var server_message = e.data;   console.log(server_message);}

Documentation: http://www.developerfusion.com/article/143158/an-introduction-to-websockets/


Websockets will be the way to go once they are more universally implemented across the major browsers - I would guess a minimum of 5 years.

The last I heard Facebook chat uses comet and a whole bunch of servers. If you want something more lightweight I can think of two options.

  1. Reduce the polling interval. This is strictly a UI issue - users may have a perfectly acceptable experience with intervals as long as a couple minutes. The only way to know for certain is through user testing, but polling every 5 seconds is probably overkill. No matter what you choose as the optimal interval, this does give you an quick way to scale if you are getting hammered - just crank up the interval until the servers stop melting.

  2. Use HTTP validation caching. You can make the requests more lightweight if the server only returns a response body when the content has changed since the last request. You will have to build something custom using ETag or Last-Modified headers and a lightweight modification checking system on the server, but it might save you a few bytes.