Skip to content

Instantly share code, notes, and snippets.

@hising
Created August 10, 2021 18:20
Show Gist options
  • Save hising/ddcb46dcb5cbb15491c3079cde0a3b86 to your computer and use it in GitHub Desktop.
Save hising/ddcb46dcb5cbb15491c3079cde0a3b86 to your computer and use it in GitHub Desktop.
Simple Game Loop in JavaScript
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