Is there a way to detect if a browser window is not currently active?

前端 未结 19 2111
无人共我
无人共我 2020-11-21 04:40

I have JavaScript that is doing activity periodically. When the user is not looking at the site (i.e., the window or tab does not have focus), it\'d be nice to not run.

19条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-21 04:55

    u can use :

    (function () {
    
        var requiredResolution = 10; // ms
        var checkInterval = 1000; // ms
        var tolerance = 20; // percent
    
    
        var counter = 0;
        var expected = checkInterval / requiredResolution;
        //console.log('expected:', expected);
    
        window.setInterval(function () {
            counter++;
        }, requiredResolution);
    
        window.setInterval(function () {
            var deviation = 100 * Math.abs(1 - counter / expected);
            // console.log('is:', counter, '(off by', deviation , '%)');
            if (deviation > tolerance) {
                console.warn('Timer resolution not sufficient!');
            }
            counter = 0;
        }, checkInterval);
    
    })();
    

提交回复
热议问题