开发者

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?


You can call animate in its completion callback.

For example:

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


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.


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();
})();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜