Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

185
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda