Gearbox
Gearbox

Reputation: 64

recursive requestAnimationFrame() javascript loop jumps directly to the end

I'm trying to learn animating in javascript.

I have a path array with x and y coordinates that I try to move through with recursion. But instead of moving the box (box[1]) one step at a time it jumps directly to the last position. If i add an alert in the loop then the animation will "work", so that it just moves the box one step at a time between each alert.

function followPath(){
    box1[1].style.left = path[index][0]+'px';
    box1[1].style.top = path[index][1]+'px';
    index++; //I put an alert("hi"); here and it "worked"
    if(index < path.length)
         requestAnimationFrame(followPath());

}

function buttonPress(){
    index = 0;
    followPath();
}

What causes this?

As a sidenote, I had the same sort of problem when i tried to pass variables to a similar recursive function that worked just fine before i tried to pass variables to it.

Thanks.

Upvotes: 0

Views: 102

Answers (1)

Marko Gresak
Marko Gresak

Reputation: 8207

Argument to requestAnimationFrame is a function, not what function returns. The line:

requestAnimationFrame(followPath());

should be

requestAnimationFrame(followPath);

Upvotes: 2

Related Questions