How to Loop a jQuery Animation Indefinitely

2018-08-16 | #jquery, #solution, #webdev

Say you have a certain jQuery-based animation you want to run indefinitely, maybe because it is a rotating wheel, maybe it's some kind of parallax scenery passing by in the background. How do you do this without having to defer to cheap tricks?

/**

* Loops an animation-based (needs to build an animation queue) closure indefinitely.

* Kills other animations on element if nothing else is declared.

* Cancel animation with .stop(true).

* The animationClosure needs to take a parameter, which is filled with the jQuery-element, this method is called upon.

*

* @param {Function} animationClosure - closure in which all animation is included, takes the jQuery-Element as first parameter, needs to do something queue-building

* @param {Function} [killAnimations=true] - defines if all current animation should be immediately finished before proceeding

* @returns {Object} this

*

* @memberof Animation:$fn.loopAnimation

* @example

* $('a').loopAnimation(function($this){ $this.animate('top', '+=10'); }, true);

**/

$.fn.loopAnimation = function(animationClosure, killAnimations){

killAnimations = (killAnimations === undefined) || !!killAnimations;

if( $.isFunction(animationClosure) ){

if( killAnimations ){

$(this).stop(true, true);

}

$(this)

.queue(function(next){

animationClosure($(this));

$(this).queue(arguments.callee);

next();

})

;

}

return this;

};

The secret sauce here is to build an infinite amount of next steps by setting next every time a new animation starts. jQuery's animation queue takes care of animation runtime an the possibility to cancel the running animation. The important thing ist actually call something on the element adding to the element's animation queue inside the animationClosure.