Looping jQuery animations indefinitely

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 —

  1. The list of animations is fired. These will be queued to be executed.
  2. Then the anonymous function itself (arguments.callee refers to the function being executed) is re-queued.
  3. next() progresses the queue. next is passed in as an argument.
This entry was posted in JavaScript and tagged , . Bookmark the permalink. Trackbacks are closed, but you can post a comment.
  • mrkbbk

    Thanks a lot!
    It seems that my brain went looping indefinitely trying to figure this out :)

  • http://www.laytonsmith.com Layton Smith

    Isn’t this prone to a stack overflow eventually? You’re calling it recursively, aren’t you?

  • Andrew

    The result is perfect. Just wondering where arguments.callee is documented, or did you look through the jquery source?

    Thank you.

    • sk89q

      It’s a JavaScript feature (the variable arguments in particular).