Jquery:用事件停止递归

时间:2012-12-05 15:30:57

标签: jquery events recursion

我递归动画3分。我想在点击#myElement后停止递归。

这是我的代码:

    $(document).ready(function(){       
        var positions = {
            'pos1': {"X": $('#point_1').css('left'), "Y": $('#point_1').css('top')},
            'pos2': {"X": $('#point_2').css('left'), "Y": $('#point_2').css('top')},
            'pos3': {"X": $('#point_3').css('left'), "Y": $('#point_3').css('top')},
        };

        animate3Points(positions);
    }); 

    function animate3Points(p) {
        animatePoints('#point_3', p, p.pos1);
        animatePoints('#point_2', p, p.pos2);
        animatePoints('#point_1', p, p.pos3);
    }

    function animatePoints(selector, p, pos) {
        $(selector).animate({
            'left': pos.X , 
            'top':  pos.Y
        }, 2000, 'easeInOutQuad', function() {

            // while #myElement has not been clicked,
            // call again animate3points for recursivity :

            if (selector == '#point_1') { // just to be recalled one time
                p2 = changePosition(p);
                animate3Points(p2);
            }

            // end while

        });
    }

    function changePosition(obj) {
        firstEl = obj.pos1;
        obj.pos1 = obj.pos2;
        obj.pos2 = obj.pos3;
        obj.pos3 = firstEl;

        return obj;
    }   

动画可以工作,但可能需要以另一种方式实现以停止递归。

一个想法?

1 个答案:

答案 0 :(得分:0)

您应该使用在函数外部实例化的全局变量,并将其用作递归调用应该停止的逻辑条件。例如:

var keepAnimating = true;

function animate3Points(p) {
    if(keepAnimating) {
        animatePoints('#point_3', p, p.pos1);
        animatePoints('#point_2', p, p.pos2);
        animatePoints('#point_1', p, p.pos3);
    }
}

在点击事件中,您需要设置keepAnimating = false;。这将停止递归,但您可能还需要停止动画。

然而,无限递归是一个非常糟糕的主意。您将导致浏览器使用大量内存。您应该优化代码以使用循环而不是递归。

相关问题