Skip to content Skip to sidebar Skip to footer

Chain Functions Unknown Number Of Times

I am animating an element's top/left css values via an unknown number of steps. I'm using the following code to store the required css values for each step of the animation: paths

Solution 1:

$element.animate(paths.shift(), function next() {
    $(this).animate(paths.shift(), paths.length && next);
});

http://jsfiddle.net/Xsz8w/2/

paths.length && next is needed to prevent infinite callback invocation.

Solution 2:

Have a recursive function instead, which calls itself until the last element of the paths array.

var paths = [{ left:-300 }, { top:-161 }, { left:-402 }];

(functionanimateNext(i){

  $element.animate(paths[i],function(){

    //on animation complete, check if the next path existsif(paths[++i]){

      // if so, let's animate using the next path
      animateNext(i);
    }
  });

//start from index 0
}(0)); 

Solution 3:

var paths = [{ left: -300 }, { top: -161 }, { left: -402 }];

(functionanimateElement(index) {
    if (paths[index] == null) return;
    $element.animate(paths[index], function () {
        animateElement(index++);
    });
})(0);

Solution 4:

You could loop each of the items and use the success function to call the next.

You could also potentially add an interval to your JSON and use animate and delay in tandem.

Solution 5:

I don't have any experience with jQuery, so I'm going to assume that you need the output from animate(a) to call the next one.

var e = $element;
for (var i = 0; i < paths.length; i++) {
    e = e.animate(paths[i]);
}

Post a Comment for "Chain Functions Unknown Number Of Times"