简体   繁体   中英

jQuery image fader doesn't stop when the window loses focus

I have a simple jQuery image fader, just cycles images in and out of focus.

Here's a pen: http://codepen.io/designsoutheast/pen/xbqjZL

Here's the code behind the fading:

        $('img.bgfade').hide();
          function anim() {
              $(".slider img.bgfade").first().appendTo('.slider').fadeOut(1000);
              $(".slider img").first().fadeIn(10);
             setTimeout(anim, 3500);
          }
          anim();
        });

It works fine, but when the window or tab loses focus for a time, and I return to it, the animation has queued and flashes different images / goes berserk until it catches up.

I've tried using the jQuery visibility plugin, but haven't been able to get it to work. I've also tried using standard (window).blur.. but I'm not sure how to properly stop the animation during that time. I've tried clearTimeout, but I think I'm doing it wrong. Here's what I've tried:

        var faderVar;

          function anim() {
              $(".slider img.bgfade").first().appendTo('.slider').fadeOut(1000);
              $(".slider img").first().fadeIn(10);
             faderVar = setTimeout(function() {anim}, 3500);
          }
          function stopFader() {
            clearTimeout(faderVar);
          }
          anim();

$(window).focus(function() {

        var faderVar;

          function anim() {
              $(".slider img.bgfade").first().appendTo('.slider').fadeOut(1000);
              $(".slider img").first().fadeIn(10);
             faderVar = setTimeout(function() {anim}, 3500);
          }
          function stopFader() {
            clearTimeout(faderVar);
          }
          anim();
        });

$(window).blur(function() {

          stopFader();

});

I THINK I'm on the right track, but I'm quite new to jQuery and I'm pretty sure the clearTimeout is written wrong. I hope someone can help!

Create a new boolean variable called 'animating' (etc.) and set it false right after 'var faderVar'. Clear that $(window).focus() function and replace it with this:

$(window).focus(function() {
    if(!animating) {
        anim();
    }
});

Set animating = true in the anim() function and animating = false in the stopFader() function. So every time you focus the $(window) it checks if anim() is running and if, not it starts the anim() function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM