开发者

Javascript, looping a set of instructions (set timeouts)

开发者 https://www.devze.com 2023-04-07 19:52 出处:网络
I want to loop an animation which is essentially changing the background-position ever 150 milliseconds. I开发者_JS百科t does not fade or anything, it just has to happen over and over again. But I can

I want to loop an animation which is essentially changing the background-position ever 150 milliseconds. I开发者_JS百科t does not fade or anything, it just has to happen over and over again. But I can not seem to find a solution that loops these set of instructions.

setTimeout( function() {
        $('div.arrow').css('backgroundPosition', '0 -47px');
    }, 150 );

setTimeout( function() {
        $('div.arrow').css('backgroundPosition', '0 -94px');
    }, 250 );

setTimeout( function() {
        $('div.arrow').css('backgroundPosition', '0 -141px');
    }, 350 );

setTimeout( function() {
        $('div.arrow').css('backgroundPosition', '0 -188px');
    }, 450 );

setTimeout( function() {
        $('div.arrow').css('backgroundPosition', '0 -235px');
    }, 550 );


Use setInterval instead of setTimeout.

Also use a global variable to see where the background image is, rather than setting lots of timeouts...

So you'll end up with something like this:

var currPos = 0;
setInterval(function(){
    currPos = currPos-47;
    if(currPos < -235){
        currPos = 0;
    }
    $('div.arrow').css('backgroundPosition','0 '+currPos+'px');
}, 150);

See example here: http://jsfiddle.net/aUBNw/


var div = $('div.arrow');
function tim(){
setTimeout( function() {
        div.css('backgroundPosition', '0 -47px');
    }, 150 );

setTimeout( function() {
        div.css('backgroundPosition', '0 -94px');
    }, 250 );

setTimeout( function() {
        div.css('backgroundPosition', '0 -141px');
    }, 350 );

setTimeout( function() {
        div.css('backgroundPosition', '0 -188px');
    }, 450 );

setTimeout( function() {
        div.css('backgroundPosition', '0 -235px');
    }, 550 );
setTimeout( function() {
        tim();
    }, 550 );
}
tim();

will simply call itself after it's completed

0

精彩评论

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