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

178
Views
Insight on weird lag in Snake Game

I'm currently working on making a web version of the Snake Game and I've got most of the pieces set up but during the gameplay, it just suddenly lags(the browser isn't lagging) and simply clicking on the page will bring it back to its normal self.

I can't figure out how to correct this issue, I'm using setTimeout to basically carry out the 'rendering' of each frame (every 100ms).

function main() {
    if (isGameOver()) return;

    setTimeout(() => {
        composeFrame();
        updateGameModels();

        main();
    }, 100);
}

I'm thinking the problem might be due to the recursive calls. Can I get some tips on how to stop the weird hanging while keeping the recursive logic or just any help.

Extra : I deployed it to GitHub pages so I can put a link here so you can run it and see the problem first-hand. You can control the snake with your KeyBoard.

Live - https://truepadawan.github.io/Snake-Game-Web/

GitHub - https://github.com/TruePadawan/Snake-Game-Web

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Thanks to @mcgraphix suggestion, I switched to using requestAnimationFrame() and it works fine now.

function main(timestamp) {
    if (isGameOver()) return;
    if (start === undefined)
    {
        start = timestamp;
    }

    let elapsedTime = timestamp - start;

    if (elapsedTime >= 100)
    {
        composeFrame();
        updateGameModels();
        start = timestamp;
    }
    window.requestAnimationFrame(main);
}
about 4 years ago · Juan Pablo Isaza Report
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!