jonagoldman
jonagoldman

Reputation: 8754

force jQuery function to infinite repeat/loop

I have this function:

    function animateImage() {
        for (i = 1; i < 31; i++) {

            top = (i * loadingHeight) + 'px';

            $(loadingDiv).animate({
                backgroundPosition: '0 -' + top
            }, 0).delay(50);

        }
    }

I want to infinite repeat/loop.

It is possible? how to do it?

Upvotes: 0

Views: 8816

Answers (3)

Ben Lee
Ben Lee

Reputation: 53319

If you just want it to animate such that it moves loadingHeight pixels up every 50 milliseconds for a total of 31 loadingHeights, and then repeats back at the starting position, then you can do that in a single animation call, and then repeat that single call, like this:

(function animateImage(steps) {
    $(loadingDiv).css('backgroundPosition', '0 0');
    $(loadingDiv).animate(
        { backgroundPosition: '0 -' + (loadingHeight * steps) + 'px' },
        { duration: 50 * steps, complete: function() { animateImage(steps); } }
    );
})(31);

The general way to do an infinite or indefinite loop in javascript is to define a function that calls itself immediately and then periodically, like this:

(function someName() {
  // do some stuff
  // then after some delay (setTimeout or animate delay, etc...), call:
  someName();
})();

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630379

After queuing your 30 50ms background changes, you can just queue the function to run again, like this:

function animateImage() {
    var div = $(loadingDiv);
    for (i = 1; i < 31; i++) {
        var top = (i * loadingHeight) + 'px';
        div.animate({ backgroundPosition: '0 -' + top }, 0).delay(50);
    }
    div.queue(function(n) { animateImage(); n(); })
}

What this does is use .queue() to call animateImage once more after all of the other queued animations run, then it'll queue up 30 more animations, etc. The other change to cache $(loadingDiv) is just an optimization, it's a independent of the loop.

Upvotes: 2

SLaks
SLaks

Reputation: 887315

You can call animate in its completion callback.

For example:

function runAnimation() {
    $(loadingDiv).animate({
        backgroundPosition: '0 -' + top
    }, runAnimation)
}

Upvotes: 4

Related Questions