Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery fadeIn fadeOut with setInterval working sporadically

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++;
        });
    });
}
like image 516
go minimal Avatar asked Nov 19 '25 22:11

go minimal


2 Answers

Have you thought about using the Cycle Plugin? It sounds like this does exactly what you're trying to do, and it offers a lot of flexibility. I've used this plugin myself with great results. Highly recommended.

like image 79
nickf Avatar answered Nov 21 '25 11:11

nickf


Just off the top of my head ... why are you doing the currentImage bookkeeping in the callback functions? It seems to me this is easier, and might even have something to do with your problem:

function changeImage()
{
    $("#img" + currentImage).fadeOut("slow");
    currentImage = (currentImage >= numImages) ? 1 : currentImage + 1;
    $("#img" + currentImage).fadeIn("slow");
}
like image 38
Jim Nelson Avatar answered Nov 21 '25 12:11

Jim Nelson