AlecDev
AlecDev

Reputation: 47

Slow down while loop to animate images sequence in Javascript

I'm working on a simple game using html css javascript, the problem when I use while loop to animate a sequence of images when I press a key, it shows only the last one I know while loop works with processor speed but I need to animate images slowly without using css animation "@keyframes". thanks

var n=0;

function rotRight()
{
    var str1 = "url(sprt/trk";
    var str2 = ".png)";
    var ss=str1.concat(n);
    
    trk.style.backgroundImage=ss.concat(str2);

    while(n!=4)
    {
        if(n>4)
        {
            n--;    
        }
        else
        {
            n++;
        }
    }  
}

Upvotes: 1

Views: 180

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075765

To do a JavaScript-based animation in the browser, you don't use a loop at all. Instead, you update the item, let the browser display that, then update it again after a delay, using setTimeout and/or requestAnimationFrame. So you might do:

let n = 0;

rotRight();

function rotRight()
{
    // Do an update
    trk.style.backgroundImage = `url(sprt/trk${n}.png)`;

    // Schedule the next if appropraite
    if (n !== 4) {
        if (n > 4) {
            n--;    
        } else {
            n++;
        }
        setTimeout(rotRight, 1000); // 1000ms = one second
    }
}

(I've also updated the code to use let and const rather than var — var has no place in modern JavaScript — and to use a template literal to build the URLs.)

But, for many animations it may be important that each update calculates where it should be in the overall animation based on time, not iterations, because various things could prevent your code being run in a timely manner. In those cases, you remember when you started, then when you're called you figure out where you should be and update accordingly. Your background swapper may not need that, but more advanced ones would.

Upvotes: 1

Related Questions