Currently my website keep auto reload a javascript function for every 10 seconds by setInterval( "checklatestmsgidLive();", 10000 );
I think the function will still keep reloading the function even when the user is viewing other website on other tab. How to make it reload the function only when the user is viewing my website? Can javascript detect if the user is viewing my website?
I saw facebook.com wall also update new posts only when I am viewing the page, when I am on other tab, it won't update the new posts. How to do that?
var tId, idleTimer;
function initReload() {
clearInterval(tId);
tId = setInterval(checklatestmsgidLive, 10000 );
}
window.onload=window.onfocus=function() {
initReload()
}
window.onblur=function() {
clearInterval(tId);
}
window.onmousemove=function() {
clearTimeout(idleTimer);
idleTimer = setTimeout(function() { clearInterval(tId);},600000); // idle for 10 minutes
}
Mouse move doesn't work very well on touch devices without a mouse, but we don't have a lot of options yet. W3C is working on a new API: Page Visibility. It's still in a very early stage, and the only browsers I could find that have started implementing it are Google Chrome (Dev Channel) and Internet Explorer 10 Platform Preview.
Since the spec is still a draft, the properties and events are vendor prefixed. But it still works, and Chrome has an extremely quick update rate. So I would try to detect if Page Visibility is available, and if not fallback to the mouse move hack.
The IE-team has a live demo that works in Chrome Dev and IE 10 platform preview.
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