Brad Sparks
Brad Sparks

Reputation: 488

Infinite Recursion using callback function in jQuery

Experimenting with jQuery and trying to make a small slide show that rotates through three images. Here's my HTML:

<div id="slideShow">
    <img src="images/slides/slide1.jpg" width="520" height="230" />
    <img src="images/slides/slide2.jpg" width="520" height="230" />
    <img src="images/slides/slide3.jpg" width="520" height="230" />       
 </div>

And here's the script:

$(function ()
{
    var $slides = $('#slideShow img').hide(),
    slideIndex = 0;

    slideTransition = function ()
    {
        slideIndex++;
        (slideIndex == $slides.length) ? slideIndex = 0: null;
        $slides.eq(slideIndex).fadeIn(3000);
        $slides.eq(slideIndex).fadeOut(3000,slideTransition);
    }

    $slides.eq(0).fadeIn(3000);
    $slides.eq(0).fadeOut(3000, slideTransition);

});

This actually works fine, but my gut is telling me that having the infinite recursion is a bad thing. Any suggestions on how to do this better?

Upvotes: 2

Views: 1306

Answers (2)

Deepak
Deepak

Reputation: 7917

To remove infinite recursion and running gallery you can use jquery' "animate" function. The reference is here http://api.jquery.com/animate/.

Upvotes: 0

Jacob
Jacob

Reputation: 78860

What you're doing is not recursion. When the animation starts, your call returns. Then, a timer event handler invokes your method. Your solution is just fine.

Upvotes: 8

Related Questions