Tuesday, April 21, 2009

AJAX update content every X seconds

I was asked several times on Twitter how to update some web page section or a block content on a page every x seconds. Some real life examples of this functionality are Twitter search results that come out when there are new tweets with search keyword or bit.ly real time link tracking that updates it’s charts every 5 seconds.

It is clear without saying that we are going to update our page content using AJAX and of course we love AJAX in jQuery flavor. So key to this functionality is JavaScript's built-in setInterval() function. It lets you to run some javascript function every X seconds. For example, the following code would pop alert box every five seconds:

setInterval( "alert('Hello')", 5000 );

Now consider we want to update shouts in our shoutbox every 10 seconds.

function updateShouts(){
    // Assuming we have #shoutbox
    $('#shoutbox').load('latestShouts.php');
}
setInterval( "updateShouts()", 10000 );

The code above will run every 10 seconds (10,000 ms) and update the contents of #shotbox with new shouts.

9 comments:

  1. I think it is better to load new request after first one finishes + 5 seconds. This is done by onComplete function in ajax call. When ajax call returns/is completed then call setTimeout(...).

    ReplyDelete
  2. use window.setInterval(updateShouts, 10000) instead. That's much faster because you don't need to eval the code..

    ReplyDelete
  3. Seems like setTimeout() is usually better as explained from SitePoint.com here:

    http://articles.sitepoint.com/article/settimeout-cleartimeout

    setInternval can cause a traffic jam of code needing to be executed whereas setTimeout() will ensures your CPU wont get buried by back logged tasks.

    ReplyDelete
  4. can the shoutbox update every 1 seconds and save in database every 5 second?

    can u explain,,

    thanks,,

    ReplyDelete
  5. Old but still good. Thanks !

    ReplyDelete
  6. I try it it dosent work..can you help me???

    ReplyDelete
  7. Hi,

    But every time you run the updateshouts function it will also repeat the previous shouts as well ?? What if you was wanting to get updates of new news stories but don't want to continually repeat the previous ones ?

    Regards

    ReplyDelete
  8. Hi,

    Where is the PHP script ?

    Regards

    ReplyDelete
  9. It would be better to use setTimeout inside of a function in case a request takes longer than the specified time like so:

    function updateShouts(){
    // Assuming we have #shoutbox
    $('#shoutbox').load('latestShouts.php');
    window.setTimeout( updateShouts, 10000 )
    }

    ReplyDelete