Assuming you want an infinite loop and are working within the scope of an object...
...
animation : ["first","second","third","etc"],
frameDelay : 400,
frameIndex : 0,
animationTimer : null,
start : function() {
// remember the scope of this object.
var handle = this;
// start the animation.
handle._nextFrame(handle);
},
_nextFrame : function(handle) {
// TODO: use frameIndex to render stuff... such as:
var animation = handle.animation[frameIndex];
$('body').html('<p>'+animation+'</p>');
// count your frames. You might add stuff to the sequence elsewhere.
var numFrames = handle.animation.length;
frameIndex = frameIndex < numFrames ? frameIndex++ : 0;
handle.animationTimer = window.setTimeout(function() {
handle._nextFrame(handle); }, handle.frameDelay);
},
_destroy : function() {
var handle = this;
clearTimeout(handle.animationTimer);
}...
Notes:
I use an old school method of underscoring private functions on an interface. You don't have to name your variables that way, and they are not private.
You will notice that I store "this" into "handle". You can't always rely on the scope of this, such as calling an object function from an event bubble, calling it from a public interface, or referencing a function internally to the object. So I just do this as a convention.
Put this code into your object, call the 'start' function, and it should continue doing its thing until you leave the page. Also, make sure to clean up your recursive timeouts, less you get an error on page refresh or page navigation.