Last active
February 18, 2025 13:10
-
-
Save luizbills/15460c1c8dc56b243b7bc366d8e615c4 to your computer and use it in GitHub Desktop.
JavaScript Game Loop
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Demo: https://jsbin.com/jumuwiyuda/edit?js,output