Skip to content

Instantly share code, notes, and snippets.

@luizbills
Last active February 18, 2025 13:10
Show Gist options
  • Save luizbills/15460c1c8dc56b243b7bc366d8e615c4 to your computer and use it in GitHub Desktop.
Save luizbills/15460c1c8dc56b243b7bc366d8e615c4 to your computer and use it in GitHub Desktop.
JavaScript Game Loop
// based on https://www.gafferongames.com/post/fix_your_timestep/
const TARGET_FPS = 60
const dt = 1/TARGET_FPS
let _accumulated = 0
let _lastFrameTime = performance.now()
/**
* @param {number} now
*/
function gameLoop (now) {
let ticks = 0,
frameTime = (now - _lastFrameTime) / 1000,
frameTimeMax = dt * 5
_lastFrameTime = now
// prevent too long loops
_accumulated += frameTime > frameTimeMax ? frameTimeMax : frameTime
while (_accumulated >= dt) {
ticks++
// update your game logic here
// end of update
_accumulated -= dt
}
if (ticks > 0) {
// draw your scene here
}
requestAnimationFrame(gameLoop)
}
requestAnimationFrame(gameLoop)
@luizbills
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment