0

I have defined a function and calling it recursive and its not working here is the code

$(document).ready(function () {
//if i remove the slider call here it doesn't even run the function slider     
slider();
    function slider() {
        $("#img2").fadeOut(3000, function () {
            $("#img2").fadeIn(3000);
        });
//recursive call
        slider();
    }
});
3
  • How have you tried to debug this? Commented Nov 5, 2013 at 14:49
  • Your recursion never end, Try console.log("something"); and see the result Commented Nov 5, 2013 at 14:49
  • You're calling slider() right after .fadeOut, but the first thing slider does is the fadeOut again. A fiddle or at least a description of what par of it isn't working would be nice. Commented Nov 5, 2013 at 14:49

2 Answers 2

8

It's working, but you call slider() again before the fadeOut has completed. Stick the recursive call in the callback:

function slider() {
    $("#img2").fadeOut(3000, function () {
        $("#img2").fadeIn(3000, function() {
            //As Kristof Feys pointed out, you probably want to wait for the 
            //fade in to complete, then call the method.
            slider();
        });
    });
}

A demo as well: http://jsfiddle.net/9k7e3/

Sign up to request clarification or add additional context in comments.

2 Comments

Wouldn't he want to call it after the fadeIn has completed rather than the fadeOut?
@KristofFeys -- Very good point, let me add a callback to the fadeIn
2

Its working just fine. You must remember the fadeOut and fadeIn function are asynchronous. Meaning, the browser does not wait until the animation is done before it executes the next line of code. So as a result, your slider() function is getting called thousands of times before the animation even completed one iteration.

If you look in the console, you will see this error being thrown:

Uncaught RangeError: Maximum call stack size exceeded

Meaning you are calling the slider function too many times. The solution is to place the slider() call inside the fadeIn callback, which will be executed only once the animation is complete.

$(document).ready(function () {
    slider();
    function slider() {
        $("#img2").fadeOut(3000, function () {
            $("#img2").fadeIn(3000, function(){
                slider();
            });
        });
    }
});

Jsfiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.