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.
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);
}