Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I move an element every x ms? [duplicate]

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

My current code:

for ( var i = 0; i <= 200; i++) {
    startPos = 300;
    nextPos = startPos;
    document.getElementById('ball').style="position:absolute; right:" + nextPos + ";";
}
like image 404
rockytez Avatar asked Nov 24 '25 23:11

rockytez


1 Answers

You can use either requestAnimationFrame or 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);
        }

    }
like image 165
Hevar Avatar answered Nov 26 '25 11:11

Hevar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!