I am animating 3 points recursively. I would like to stop recursion after clicking #myElement.
Here is my code:
$(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;
}
Animation works but need maybe to be implemented in another way to stop recursion.
An idea ?
You should make use of a global variable instantiated outside your function and use it as the logical conditional for when the recursive calls should stop. For instance:
On your click event, you need to set
keepAnimating = false;. This will stop the recursion, but you may also need to stop the animation.However, infinite recursion is a really bad idea. You will cause the browser to use a lot of memory. You should optimize your code to use loops instead of recursion.