user2724072 user2724072 - 15 days ago 5
CSS Question

setInterval for css sprite animation

I'm trying to animate a sprite using the below code but instead of waiting about 1 second before going to the next iteration of the loop, the animation seems to jump from the first image in the sprite to the last within about a second. Can anyone tell me how I might be able to alter the code to make it work the way I have in mind? Thanks!

preview = setInterval(animation,1000);
counter = 0;

function animation() {
while (counter < 81){
position = counter * 1.25;
$('#ad_1').css({"background-position" : position + "% 0%"});
counter ++;
}
};

preview;

Answer

Take the while portion of the loop out.

function animation() {
    if (counter < 81){
        position = counter * 1.25;
        $('#ad_1').css({"background-position" : position + "% 0%"});
        counter ++;
    } else {
         clearInterval(preview); /* this will stop the interval timer, since you won't need it after 80 repetitions. */
         preview = null;
    }
}
Comments