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 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?
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?
Share Improve this question asked Jun 10, 2011 at 14:56 zac1987zac1987 2,7779 gold badges47 silver badges62 bronze badges 3- possible duplicate of Is there a way to detect if a browser window is not currently active? – Lazarus Commented Jun 10, 2011 at 14:59
- 1 arrrr.. sorry about it. I feel guilty (T_T). – zac1987 Commented Jun 10, 2011 at 15:32
- 1 Don't feel guilty, it could happen to anyone. I am impressed that no-one else cared and some people got the opportunity to gain some rep from answering it again. I love SO sometimes... sometimes not. – Lazarus Commented Jun 13, 2011 at 14:45
3 Answers
Reset to default 9var 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.
An easy solution would be to detect a mouse move in your page.