I’ve been using an ajax call to refresh certain elements of my webapp every 5 seconds. I had no problem using setInterval(refreshElements, 5000) to achieve this.
Now I want to take into account if the user is actually at the page. I managed to detect this using the ‘focus’ and ‘blur’ events. However, the following code does work as I intended. I want refreshElements() to be called every 5 seconds if the user is on the page, but be called every 15 seconds if the user is not on the page.
What happens right now is that the timer appears to freeze unless I’m viewing the page. I’ve verified this behavior with Firebug. I see GET calls every 5 seconds, but once I switch to another tab, no more GET’s are called until I switch back to the original tab. Any ideas?
Here’s the code:
$(document).ready(function(){
var refreshinterval = 5000;
var timer;
$(window).bind("blur", function() {
refreshinterval = 15000;
});
$(window).bind("focus", function() {
refreshinterval = 5000;
});
function refreshElements(){
clearTimeout(timer);
$.ajax({
type: "GET",
dataType: 'json',
url: "refresh_url",
cache: false,
success: function(data){
// fill the desired page elements
}
});
timer = setTimeout(refreshElements, refreshinterval);
}
refreshElements();
});
It was a problem with Firebug. After running more tests with the code. I realized my app WAS behaving properly. Firebug would stop capturing the GET requests if the browser window lost focus.
I tried Developer Tools in Chrome and it continued to capture the GET requests even if Chrome was in the background.
In addition, I noticed that the Chrome Developer Tools frame can remove focus from the webpage you’re viewing.
All in all it’s been an enlightening 24 hours. I hope the helps someone in the future!