Is there a simple way to make a game loop in JavaScript? something like...
onTimerTick() {
// update game state
}
Many of these answers are outdated and suboptimal. The recommended way to do this now is using requestAnimationFrame
.
For example:
let previousTime = 0.0;
const loop = time => {
// Compute the delta-time against the previous time
const dt = time - previousTime;
// Update the previous time
previousTime = time;
// Update your game
update(dt);
// Render your game
render();
// Repeat
window.requestAnimationFrame(loop);
};
// Launch
window.requestAnimationFrame(time => {
previousTime = time;
window.requestAnimationFrame(loop);
});