While implementing auto refreshing div in jQuery that fetches updates on posts periodically as can be seen on Twitter, Facebook etc.
I had to think about making the refresh as efficient as possible. I decided to send a request to the server every 30 seconds - 1 minute. And, the request will be sent only if the browser window is active.
var postUpdateIntervalID;
var interval = 30000;
$(window).load(function(){
if (!postUpdateIntervalID) {
postUpdateIntervalID = setInterval(function() {
updatePostsList();
}, interval);
}
});
$(window).focus(function(){
if (!postUpdateIntervalID) {
updatePostsList();
postUpdateIntervalID = setInterval(function() {
updatePostsList();
}, interval);
}
});
$(window).blur(function() {
clearInterval(postUpdateIntervalID);
postUpdateIntervalID = 0;
});
function updatePostsList() {
// Sends a request to the server to fetch new posts.
}
- On load, set interval of 30 seconds to call
updatePostsList
. - On focus, call
updatePostsList
immediately. Then, set interval as above. - On blur, reset the interval.