How do I move an element every x ms?

I have an element that I want to move 200px to the right and I want it to move pixels every X ms (if possible).

My current code:

for ( var i = 0; i <= 200; i++) {
    startPos = 300;
    nextPos = startPos;
    document.getElementById('ball').style="position:absolute; right:" + nextPos + ";";
}

      

+3


source to share


1 answer


You can use either or . requestAnimationFrame

setTimeout

for ( var i = 0; i <= 200; i++) {
        startPos = 300;
        nextPos = startPos;
        document.getElementById('ball').style="position:absolute; right:" + nextPos + ";";
    }

      

SetTimeout:



var ball = document.getElementById('ball');
ball.style.position = 'absolute';

var interval = 10; // your X MS
var distance = 0;

var ticker = setInterval(moveBall, interval); // this function will run every 10ms till the clearInterval() is called.

function moveBall() {
    if(distance < 200) {
        distance++;
        ball.style.right = 300 + distance + "px";
    } 
    else {
        clearInterval(ticker);
    }

}

      

requestAnimationFrame:

var ball = document.getElementById('ball');
    ball.style.position = 'absolute';

    var distance = 0;

requestAnimationFrame(moveBall);

function moveBall() {
        if(distance < 200) {
            distance++;
            ball.style.right = 300 + distance + "px";
            requestAnimationFrame(moveball);
        } 
        else {
            cancelAnimationFrame(moveBall);
        }

    }

      

+2


source







All Articles