Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

225
Views
Javascript - simple requestAnimationFrame gameloop

I'm going to make this very simple. Every frame, I need to render the 'player' wherever they are. Using setInterval, I was able to do this. Unfortunately, that causes it to occasionally flicker and my many hours trying to correct this have been unsuccessful. I've narrowed down the problem to inside this code:

function eachFrame(){
    ctx.clearRect(0,0,canvas.width,canvas.height);
    player.motion();
    player.render();
    setTimeout(window.requestAnimationFrame(eachFrame), 1000 / fps);
};

window.requestAnimationFrame(eachFrame);

When this runs, absolutely nothing appears onscreen.

player.motion updates the player position and handle movement logic. It is not the issue, but I need it.

player.render draws the current player position on the screen. It also is not the problem.

The reason I know player.motion and player.render are completely fine is because, when you get rid of ctx.clearRect(), you can move the player around and it renders perfectly.

function eachFrame(){
    //ctx.clearRect(0,0,canvas.width,canvas.height);
    player.motion();
    player.render();
    setTimeout(window.requestAnimationFrame(eachFrame), 1000 / fps);
};

window.requestAnimationFrame(eachFrame);

When you get rid of that, of course you're now playing snake and you're left with a trail behind the player. ctx.clearRect does it's job, it clears the screen.

This line is the problem: setTimeout(window.requestAnimationFrame(eachFrame), 1000 / fps);

How do I fix it?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!