简体   繁体   中英

jQuery increment variable in recursive function

There are other questions with almost the same title as this but they don't seem to answer my question.

I am trying to make a simple javascript function that uses jQuery to fade div blocks in and out one after the other, and goes back to the first div once it get's to the end. This should continue while the user is on the page, much like a slideshow.

There are 5 'slides' or divs to be shown and hidden in sequence. They have the classes 'content1', 'content2', 'content3' etc.

$(document).ready(function() {

            var slide = 1;
            nextSlide(slide);

            function nextSlide(slide) {
                $('.content' + slide.toString()).fadeTo(2000, 1.0).delay(5000).fadeTo(2000, 0.0).delay(2000);

                if(slide > 5) {
                    slide = 1;
                } else {
                    slide++;
                }

                nextSlide(slide);
            };
        });

This does not fade each div in and out in sequence, what it actually does is fade all of the slides in and out simultaneously.

How do I get it to reference each slides class in turn and then loop back to the first slide?

Many thanks.

Your function will recurse immediately, dispatching all of the animation requests around the same time.

To stagger them, you should recurse with a timeout :

$(document).ready(function() {

        var slide = 1;
        nextSlide();

        function nextSlide() {
            $('.content' + slide.toString()).fadeTo(2000, 1.0).delay(5000).fadeTo(2000, 0.0).delay(2000);

            if(slide > 5) {
                slide = 1;
            } else {
                slide++;
            }

            setTimeout(nextSlide, 2000); // second param is delay in ms
        };
    });

This will cause the next call to occur after 2000ms. Thanks to closure, your slide variable should be captured and will persist its value between calls.

No need for a timeout. Simply call the next iteration as a callback of the last fadeTo method:

$(document).ready(function() {

        var slide = 1;
        nextSlide(slide);

        function nextSlide(slide) {
            $('.content' + slide.toString())
            .fadeTo(2000, 1.0)
            .delay(5000)
            .fadeTo(2000, 0.0, function(){
                if(slide > 5) {
                    slide = 1;
                } else {
                   slide++;
                }
                nextSlide(slide);
            });                
        };

});

http://jsfiddle.net/3L09b505/

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