A friend asked how to loop a jQuery animation after he had attempted to queue the animations using an unending while loop. That doesn’t work as JavaScript is not threaded and it’d only end up blocking forever, creating an ever growing queue of animations that would never be run. Two better ways to loop an animation are (1) to use a timer on an interval that re-queues the animations, or (2) to use a callback on the last animation in the sequence to re-queue the animations. The first solution isn’t the same as the latter, as the latter will fire immediately after the first run finishes.
However, I suggested that he queue a function as if it was an animation itself, and use that to fire off the animations each run. That is illustrated below.
[cc lang="javascript"]$(“#image”).queue(function(next) {
$(this).fadeIn(1000).delay(500).fadeOut(1000);
$(this).queue(arguments.callee);
next();
});[/cc]
The snippet is simple —
- The list of animations is fired. These will be queued to be executed.
- Then the anonymous function itself (arguments.callee refers to the function being executed) is re-queued.
- next() progresses the queue.
nextis passed in as an argument.
