Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 138221

JQuery fadeIn fadeOut with setInterval working sporadically

$
0
0

I have a bunch of images that need to rotate in and out one at a time every 2 seconds with fancy JQuery fadeIn and fadeOut. I have all the images in the HTML to pre-load them and a setInterval timer that fades the current image out, then fades the next image in. Problem is that sometimes when you are clicking or scrolling during the fade in/out process, the JS gets interrupted and the current image never disappears and the next one fades in giving you two images.

I get the feeling it has something to do with setInterval not running properly every 2 seconds, but are there any better ways to accomplish what I need?

Here's a snippet of code:

HTML

<a href="javascript:;">
  <img id="img1" src="image1.gif" />
  <img id="img2" src="image2.gif" style="display:none;" />
  <img id="img3" src="image3.gif" style="display:none;" />
</a>

JS

var numImages = 3;
var currentImage = 1;
imageInterval = window.setInterval("changeImage();", 2000);

function changeImage()
{
    $("#img" + currentImage).fadeOut("slow", function() {
        if (currentImage >= numImages)
        {
            currentImage = 0;
        }
        $("#img" + (currentImage + 1) ).fadeIn("slow", function() {
            currentImage++;
        });
    });
}

Viewing all articles
Browse latest Browse all 138221

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>