Here’s the basic idea of what I’m trying to do:
- Set the innerHTML of a DIV to some value X
- Animate the DIV
- When the animation finishes, change the value of X and repeat N times
If I do this in a loop, what ends up happening is, because the animations occur asynchronously, the loop finishes and the DIV is set to its final value before the animations have had a chance to run for each value of X.
As this question notes, the best way to solve this problem is to make a recursive call to the function in the callback handler for the animation. This way the value of the DIV doesn’t change until the animation of the previous value is complete.
This works perfectly…to a point. If I animate a bunch of these DIVs at the same time, my browser gets overwhelmed and crashes. Too much recursion.
Can anyone think of a way to do this without using recursion?
EDIT:
Here’s my code:
- Recursion: http://jsfiddle.net/W7aFm/
- setInterval: http://jsfiddle.net/2HYYm/
Using setInterval, you should be able to do something like the following. There’s no recursion taking place at all. (Of course, this example is contrived, but should explain the concept.)
Working example: http://jsfiddle.net/TNwAZ/1/
HTML
Javascript
EDIT:
Not sure how you are getting the elements to animate, but here’s an example of placing references to them in an array, and looping over that.
http://jsfiddle.net/TNwAZ/3/
HTML
Javascript
EDIT:
This version skips the
forloop, and just gets a collection of jQuery objects, and passes that in.http://jsfiddle.net/TNwAZ/5/
HTML
Javascript