Nikas music and gaming
Nikas music and gaming

Reputation: 1282

Slideshow with setInterval

I want to make a game when in the intro there's a slideshow with images.

Here my code:

$("#intro-vid").bind("ended", function() {
      intro_music.play();
      $('#intro-vid').hide();
      $('#intro-img-1').fadeIn("slow");
      setTimeout(function() {
        $('#intro-img-1').fadeOut("slow");
        $('#intro-img-2').fadeIn("slow");
        setTimeout(function() {
          $('#intro-img-2').fadeOut("slow");
          $('#intro-img-3').fadeIn("slow");
          setTimeout(function() {
            $('#intro-img-3').fadeOut("slow");
            $('#intro-img-4').fadeIn("slow");
            setTimeout(function() {
              $('#intro-img-4').fadeOut("slow");
              $('#intro-img-5').fadeIn("slow");
            }, 1800);
          }, 1900);
        }, 1950);
      }, 2000);
});

What I'm doing here is when intro video ends, I hide the video, playing the music and then displaying the slideshow.

But the problem that this code is really big and I would want to create some sort of setInterval() and then when all the images end I would want to stop this with clearInterval()

And every image has it own id and all of them have a class name, and i need that every time the setTimeout() will be more and more faster every time

           }, 1800);
          }, 1900);
        }, 1950);
      }, 2000);

Upvotes: 1

Views: 127

Answers (1)

Roland Ruul
Roland Ruul

Reputation: 1242

You could make a function that calculates setInterval's interval and currently shown image number.

Eg

$("#intro-vid").bind("ended", function() {
    intro_music.play();
    $('#intro-img-1').fadeIn('slow');
    slideShow(1950, 50, 4, 2);
});


//  Slideshow
function slideShow(interval, intervalStep, maxIterations, iteration) {

    setTimeout(function() {
        //  Do stuff
        if (iteration < 2) {
            $('#intro-img-' + iteration).fadeIn('slow');
        } else {
            $('#intro-img-' + (iteration - 1)).fadeOut('slow');
            $('#intro-img-' + iteration).fadeIn('slow');
        }

        //  Check iteration count
        if (maxIterations > 1) {
            slideShow(interval - intervalStep, intervalStep, maxIterations - 1, iteration + 1);
        }
    }, interval);

}

Working example in jsfiddle

Upvotes: 2

Related Questions