0

I have this timer (see Code below). How can I make sure that the countdown starts AND keeps counting down only if the browser window is onFocus?

(I want it to pause if the user opens another window, for example.)

//Countdown

function timerCountdown()
{
    x=100;
    document.getElementById('timer1').value=x;
    x=x-1;
    t=setTimeout("timerCountdown()",1000);

    if (c<-1)
    {
        document.getElementById('timer1').value='Go';
        clearTimeout(t);

    }
}
Ilmari Karonen
  • 49,047
  • 9
  • 93
  • 153
eric01
  • 909
  • 3
  • 8
  • 20
  • possible duplicate of [Is there a way to detect if a browser window is not currently active?](http://stackoverflow.com/questions/1060008/is-there-a-way-to-detect-if-a-browser-window-is-not-currently-active) – Phil Mar 06 '12 at 03:07

1 Answers1

1
window.onblur = function() {
  // Stop counting
}

window.onfocus = function() {
  // Start counting
}
ijse
  • 2,998
  • 1
  • 19
  • 25
  • Hi, Thanks for your response. I actually used the original code but added the onblur and onfocus inthe the body tag. See below – eric01 Mar 06 '12 at 03:49
  • Thanks for your response. I kind of found a way to do that but it's still causing me a little problem: I created a function function stopCounter(){ clearTimeout(t); x=x+1 } Then, when I change the body tag to that: It does what I want but it doesn't start on it own. It waits for me to Blur then reFocus on the current page. And if I try this: The timer starts going very fast. And it goes even faster when I refresh the page. Any suggestion? Thanks! – eric01 Mar 06 '12 at 03:55
  • check state before start/stop counting. `clearTimeout()` when it is the time. – ijse Mar 09 '12 at 11:38