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.
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(...).
ReplyDeleteuse window.setInterval(updateShouts, 10000) instead. That's much faster because you don't need to eval the code..
ReplyDeleteSeems like setTimeout() is usually better as explained from SitePoint.com here:
ReplyDeletehttp://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.
can the shoutbox update every 1 seconds and save in database every 5 second?
ReplyDeletecan u explain,,
thanks,,
Old but still good. Thanks !
ReplyDeleteI try it it dosent work..can you help me???
ReplyDeleteHi,
ReplyDeleteBut 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
Hi,
ReplyDeleteWhere is the PHP script ?
Regards
It would be better to use setTimeout inside of a function in case a request takes longer than the specified time like so:
ReplyDeletefunction updateShouts(){
// Assuming we have #shoutbox
$('#shoutbox').load('latestShouts.php');
window.setTimeout( updateShouts, 10000 )
}