Oliver Sewell
Oliver Sewell

Reputation: 137

update value of global variable inside requestAnimationFrame

I'm trying to update a global value inside of a request Animation frame function and get the updated value out. how do I do this

var flyPos;

function drawFrame() {
 window.requestAnimationFrame(drawFrame);
 transX = Math.sin(angleX) * range;
 transY = Math.sin(angleY) * range;
 fly.style.transform = `translate3d(${transX}px,${transY}px,0)`
 angleX += xspeed;
 angleY += yspeed;
 flyPos = fly.getBoundingClientRect();
 return flyPos;

/* i think this is scoping issue*/ }

window.requestAnimationFrame(drawFrame);

console.log(flyPos);

this should look the position of the fly each time the animation frame runs

Upvotes: 1

Views: 899

Answers (1)

user663031
user663031

Reputation:

/* i think this is scoping issue*/

It's not a scoping issue. It's a timing issue. flyPos is not going to be set until the callback you pass to rAF runs, which is going to be after your console.log.

If you want to log the position of the fly each time the rAF callback runs, then put the console.log inside the callback.

Upvotes: 2

Related Questions