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

后端 未结 2 724
失恋的感觉
失恋的感觉 2020-12-31 12:13

Building a social network, I\'m trying to fetch live notifications. Currently, the site sends an AJAX request every few seconds using setInterval. It looks something like th

2条回答
  •  孤城傲影
    2020-12-31 13:00

    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.

提交回复
热议问题