Is there a better way to create asynchronous updates without using setInterval?

I have several parts of my site that check for updates every half second, so it can alert you to messages etc. However, I feel like using $ .post with setInterval can be a little heavy on the site. Is there an alternative method that is recommended for these tasks?


source to share

2 answers would be a way if you are using nodeJS . If not, check out this jQuery plugin , it has a graceful degradation even though it's not as comprehensive as



Yes, although it's not trivial.

The best approach

You can use a long poll (or "comet") that opens a connection, keeps it open for 20 seconds or so, and immediately reopens it. The server can send anything at any time.

Newer browsers provide web sites that provide persistent connections.

Both are relatively complex to code, so you need some kind of structure to handle things for you. Also, the connection has to be open for every user, so it really only works with something lightweight like NodeJS.

A lighter approach

If you want to make something easier to implement, I would recommend checking for updates as you suggested (called a short poll to contrast with long polls / websites). You can make a simple survey solution like this:

window.setInterval(function () {
  // More lightweight than $.post
  $.get('/datasource', function () {
    /* do something */
}, 3000);


Intervals of 3 seconds were previously used for high profile people .

If the situation is slow, try profiling the database queries in / datasource



All Articles