Oliver Sewell Oliver Sewell - 5 months ago 29
Javascript Question

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() {
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*/



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

Answer Source

/* 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download