Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Content reloading after x seconds

Tags:

jquery

In my index page, there is a div box that shows the last posts on a forum. I want it to be reloaded every 10 seconds.

$(document).ready(function(){
     while(1==1)
     {
        $("#lastPosts").delay(10000).load("showLastPosts.php");
     }
});

Is this a good idea? Is there a better approach?

like image 786
user1091856 Avatar asked Mar 17 '26 14:03

user1091856


1 Answers

Try setInterval instead:

$(document).ready(function(){
    setInterval(function () {
        $("#lastPosts").load("showLastPosts.php");
    }, 10000);
});

Since you're loading remote content, you should also consider the possibility that the AJAX calls could come back in different orders (unlikely, since your interval is 10 seconds). To protect against this, you can use setTimeout and a recursive function (as outlined at the bottom of the MDN article):

(function getLatestPosts(){  
   setTimeout(function(){   
      $("#latestPosts").load("showLastPosts.php", getLatestPosts);     
  }, 10000);  
})();  
like image 173
Andrew Whitaker Avatar answered Mar 19 '26 06:03

Andrew Whitaker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!