pagehide and pageshow events don't work as expected on ios chrome
Below is the working code:
<script type="text/javascript">
var heartbeat;
var lastInterval;
function clearTimers() {
clearTimeout(heartbeat);
}
function getTime() {
return (new Date()).getTime();
}
function intervalHeartbeat() {
var now = getTime();
var diff = now - lastInterval - 200;
lastInterval = now;
if(diff > 1000) { // don't trigger on small stutters less than 1000ms
clearTimers();
}
}
lastInterval = getTime();
heartbeat = setInterval(intervalHeartbeat, 200);
You can find more details here: http://aawaara.com/post/74543339755/smallest-piece-of-code-thats-going-to-change-the-world
Pagehide and pageshow aren't the events you need for what you're trying to accomplish.
Instead, use the visibilitychange
event in combination with document.hidden
or document.visibilitystate
, which should do exactly what you want.
This'll only work on supported browsers - which to date includes Chrome, but not Safari (yet). So to be safe, I'd call clearTimers()
on visibilitychange
, and fall back to calling it on pagehide
only if document.visibilitystate is not defined.
See:
MDN: Using the Page Visibility API
Page Visibility - W3C recommendation, October 2013