0

I have a function applied to setInterval function. When I minimize or change the focused window, then get back to the browser showing my web site, the browser plays everything that happened since i changed the focus to another window, in a very fast manner.

Is there a way to hold the animations, setintervals when window of focus in windows change ?

Thanks.

Ozum Safa
  • 1,458
  • 2
  • 15
  • 27

3 Answers3

0

I found this post: JavaScript / jQuery: Test if window has focus

for me it worked on google chrome but it could be that it doesn't work in some browsers.

Here is a fiddle to test:

http://jsfiddle.net/ScKbk/

His answer:

var window_focus;

$(window).focus(function() {
    window_focus = true;
})

.blur(function() {
    window_focus = false;
});

$(document).one('click',function() {
   setInterval(function() { $('body').append('has focus? ' + window_focus + '<br>'); }, 1000);
});​
Community
  • 1
  • 1
Getu.ch
  • 94
  • 5
0

Try this.

    var handeler;
    function ShowAnimation()
{
    //SetInterval code
    handeler = SetInterval(myfunction, 1000);
}



//clear the handler when not in use.
function Clearhandler()
{
 ClearTimeout(handeler);
}



 //call the above method on the onblur event of window.
  $(window).focus(ShowAnimation(),Clearhandler());
sudhansu63
  • 6,025
  • 4
  • 39
  • 52
0

Much like Getu.ch answer except this will only execute your "work" code if the window has focus (runs every 3 seconds). Not tested in all browsers but here is a link showing browser compatibility of window.focus / window.blur

 (function($) {

     var windowHasFocus = false;

     $(window).focus(function() {
        windowHasFocus = true;
     });

     $(window).blur(function () {
        windowHasFocus = false;
     });

     setInterval(function() { 
         if(windowHasFocus) {
            //Do your work
         }
     }, 3000);

});
JBeagle
  • 2,630
  • 2
  • 18
  • 20