Is it possible, in JavaScript, to detect when the screen is turned off in the Android & iOS browsers

后端 未结 4 809
暖寄归人
暖寄归人 2020-12-03 17:06

I was tracking down some ridiculously high load times that my app\'s javascript reported, and found that Android (and iOS) pause some JavaScript execution when the window is

4条回答
  •  一向
    一向 (楼主)
    2020-12-03 17:37

    I just found a pretty good solution for my use case:

    function getTime() {
        return (new Date()).getTime();
    }
    
    var lastInterval = getTime();
    
    function intervalHeartbeat() {
        var now = getTime();
        var diff = now - lastInterval;
        var offBy = diff - 1000; // 1000 = the 1 second delay I was expecting
        lastInterval = now;
    
        if(offBy > 100) { // don't trigger on small stutters less than 100ms
            console.log('interval heartbeat - off by ' + offBy + 'ms');
        }
    }
    
    setInterval(intervalHeartbeat, 1000);
    

    When the screen is turned off (or JS is paused for any reason), the next interval is delayed until JS execution resumes. In my code, I can just adjust the timers by the offBy amount and call it good.

    In quick testing, this seemed to work well on both Android 4.2.2's browser and Safari on iOS 6.1.3.

提交回复
热议问题