How to use a function with paramters inside RequestAnimationFrame?

269 views Asked by At

Okay so I have search all around stack overflow and the web for how to use RequestAnimationFrame and include a function WITH PARAMETERS so here is my problem with codes

requestAnimationFrame(move);
function move(speed) {
    blackSquare.position.y -= 1;
    var moveBS = blackSquare.position.y - 12.5;
    //"stoping it from moving" //begin
    if (moveBS > 0) {
    requestAnimationFrame(move);
    moveBS = blackSquare.position.y + 12.5;
    }
    else {
        console.log("SUCCESS!");
    }
    //"stoping it from moving" //ends
}

This works but I want "move" to have parameters so when I try

requestAnimationFrame(move(1));
function move(speed) {
    blackSquare.position.y -= speed;
    var moveBS = blackSquare.position.y - 12.5;
    //"stoping it from moving" //begin
    if (moveBS > 0) {
    requestAnimationFrame(move);
    moveBS = blackSquare.position.y + 12.5;
    }
    else {
        console.log("SUCCESS!");
    }
    //"stoping it from moving" //ends
}

My blackSquare appears for a split of a second and then disappears. Over the Chrome Console appears the error "Uncaught TypeError: Type error" that points out to the first line in the second provided code. And followed by "SUCCESS!"

    requestAnimationFrame(move(1));
function move(speed) {
    blackSquare.position.y -= speed;
    var moveBS = blackSquare.position.y - 12.5;
    //"stoping it from moving" //begin
    if (moveBS > 0) {
    requestAnimationFrame(move(1));
    moveBS = blackSquare.position.y + 12.5;
    }
    else {
        console.log("SUCCESS!");
    }
    //"stoping it from moving" //ends
}

While as when I change both, the results are slightly different since the square disappears and then appears in no time at the end of the screen (What I intended but slowly with animation) And the console log looks like this

SUCCESS!
Uncaught TypeError: Type error

instead of

Uncaught TypeError: Type error
SUCCESS!

Can someone help me to make this work and enlighten me what exactly happened in my codes?

2

There are 2 answers

1
Julio On

I believe you can do something like:

var move_param = 1; // Whatever your move parameter needs to be

requestAnimationFrame(function() {
    move(move_param);
});

Here you're passing an anonymous function to the requestAnimationFrame, which in turn makes the call to move with the provided parameter.

0
Gray On

When you call requestAnimationFrame(move(1));, you are actually calling the move function. What you need to do is pass a reference to the move function. When requestAnimationFrame is called, it calls your function with a single parameter, which is the time that the frame is scheduled to draw in milliseconds.