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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.