0

I got 3 frames to my animation and I'm trying to get it to play correctly. BUt, it will only play 1 frame of the animation. Here is my code:

function playHomeAnimation(){
    var timer =0;
    timer+=1;
    if(timer==0){
        document.getElementById('home').src="home3.jpg";
    }
    else if(timer==1){
        document.getElementById('home').src="home2.jpg";
    }
    else if(timer==2){
        document.getElementById('home').src="home1.jpg";
    }
    else if(timer>=3){
        timer = 3;
    }
    else{
        document.getElementById('home').src="home1.jpg";
    }

    setTimeout(playHomeAnimation(), 400);
    playHomeAnimation();
}
2
Contributors
1
Reply
2
Views
5 Years
Discussion Span
Last Post by Airshow
0

It's better to find the image element in the DOM just once rather than every time the image needs to be changed.

You can also pass objects/values into the function as parameters. This avoids having to set global variables.

//this version will play once
function playHomeAnimation(imageElement, n, t) {
    imageElement.src = "home" + n + ".jpg";
    n = (n - 1);
    if(n !< 0) {
        setTimeout(function(){ playHomeAnimation(imageElement, n, t) }, t);
    }
}
playHomeAnimation(document.getElementById('home'), 3, 400);

//this version will repeat indefinitely
function playHomeAnimation(imageElement, n, t) {
    imageElement.src = "home" + n + ".jpg";
    n = (n - 1);
    if(n < 0) { n = 3; }
    setTimeout(function(){ playHomeAnimation(imageElement, n, t) }, t);
}
playHomeAnimation(document.getElementById('home'), 3, 400);

Note how the parameters are passed through to the next function call in the setTimeout statement. n is modified to achieve the animation effect.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.