1

I want to stop timer when browser tab is inactive or minimize but the issue is when I change browser tab or minimize and after maximize browser tab, count of timer display two time in the window body. Kindly suggest the solution

var window_focus;    
$(window).focus(function() {
    window_focus = true;
    startCount();
});
$(window).blur(function() {
    window_focus = false;
    stopCount(); 
});
var c = 0;
var t;
var timer_is_on = 0;

function timedCount()
{
    c = c+1;
    t = setTimeout(function(){timedCount()},1000);    
}

function startCount()
{
    if (!timer_is_on)
    {
        timer_is_on=1;
        timedCount();
    }
}

function stopCount()
{
    clearTimeout(t);
    timer_is_on=0; 
    $('body').append('count' + c + '<br>');        
}
BenMorel
  • 34,448
  • 50
  • 182
  • 322
okconfused
  • 3,567
  • 4
  • 25
  • 38

1 Answers1

6

The only reliable way to do so is to use Visibility API offered by HTML5, it offers various ways to check browser visibility status.

for ex:

document.hidden // Returns true if the page is hidden

and

document.visibilityState // Returns a string telling state of visibility

also you can add listener on change of browser visibility states as follows :

document.addEventListener("visibilitychange", function() {
  console.log(document.hidden, document.visibilityState);
}, false);

but this does not work in all browsers, so you need to test this in multiple browsers before starting on this.

Sunil Verma
  • 2,490
  • 1
  • 14
  • 15