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?
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);
})();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With