drakzuli
drakzuli

Reputation: 43

Is this the proper way to use requestAnimationFrame?

I have a piece of software that I wrote which fires repaints of the screen as soon as the updating logic is finished. The issue is that the updating logic happens over 1000 times per second. The browser cannot update the screen this quickly, so I figured that a requestAnimationFrame would allow me to update the screen for the user in a slower manner.

I structured the code like so:

function repaint(){
   now = Date.now();
   elapsed = now-then;
   if(elapsed > 2000){
   .
   .
   .
   //animation goes here
   .
   .
   .
   then = Date.now();
   }

}

function startRepaint(){
   then = Date.now();
   requestAnimationFrame(repaint);
}

while(count < 1000){
   .
   .
   .
   startRepaint();
   .
   .
   .
}

Can I use requestAnimationFrame in this way to achieve my desired functionality?

Upvotes: 2

Views: 229

Answers (1)

Dan Mullin
Dan Mullin

Reputation: 4435

What you have here is not what you’re looking for.

Every time you go through the while loop, you call startRepaint() which sends off a request for an animation frame.

After the first call to that function you go through the while loop and call it again. By the time you have called this function a second time, you may not have received your first animation frame yet.

Ideally, you want to set it up so that you call an update function which in turn sends the next request.

function repaint() {
    ...
    requestAnimationFrame(repaint);
}

Doing it this way ensures that you always complete a full frame of your code before trying to start the next one.

You could use a counter variable in the repaint function to track the iterations.

Upvotes: 1

Related Questions