Created
August 10, 2021 18:20
-
-
Save hising/ddcb46dcb5cbb15491c3079cde0a3b86 to your computer and use it in GitHub Desktop.
Simple Game Loop in JavaScript
This file contains 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
let previousTime = 0.0; | |
let isGameRunning = true; | |
const update = (diff) => { | |
console.log(diff); | |
}; | |
const render = () => { }; | |
const loop = time => { | |
const dt = time - previousTime; | |
previousTime = time; | |
update(dt); | |
render(); | |
isGameRunning && window.requestAnimationFrame(loop); | |
}; | |
// Launch | |
window.requestAnimationFrame(time => { | |
previousTime = time; | |
window.requestAnimationFrame(loop); | |
}); | |
document.addEventListener("DOMContentLoaded", (event) => { | |
document.getElementById("pause").addEventListener("click", (event) => { | |
event.preventDefault(); | |
isGameRunning = false; | |
}); | |
document.getElementById("play").addEventListener("click", (event) => { | |
event.preventDefault(); | |
isGameRunning = true; | |
window.requestAnimationFrame(loop); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment