JavaScript中的递归调用不起作用?

JavaScript中的递归调用不起作用?,javascript,jquery,recursion,Javascript,Jquery,Recursion,我定义了一个函数,并将其称为递归函数,但它不起作用 这是密码 $(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").fad

我定义了一个函数,并将其称为递归函数,但它不起作用 这是密码

$(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();
    }
});

它正在工作,但在
淡出
完成之前再次调用
slider()
。将递归调用粘贴到回调中:

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();
        });
    });
}

还有一个演示:

工作正常。您必须记住,
fadeOut
fadeIn
功能是异步的。这意味着,浏览器不会等到动画完成后才执行下一行代码。因此,您的
slider()
函数在动画完成一次迭代之前被调用了数千次

如果查看控制台,您将看到抛出以下错误:

Uncaught RangeError: Maximum call stack size exceeded
这意味着您调用
滑块
函数的次数太多。解决方案是将
slider()
调用放在
fadeIn
回调中,该回调仅在动画完成后执行

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

您是如何调试的?您的递归永远不会结束,请尝试console.log(“某物”);查看您在
.fadeOut
之后调用
滑块()
的结果,但滑块所做的第一件事是再次调用
fadeOut
。一个小提琴或至少一个关于它的PAR不工作的描述将是很好的。在FADEIN完成而不是FAEDUT之后,他不想调用它吗?@ KristofFeys,非常好的一点,让我添加一个回调到<代码> FADEIN < /代码> @ KristofFeys -编辑: