Skip to content

Instantly share code, notes, and snippets.

@cezary
Last active March 14, 2017 21:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cezary/332b9739a94abff7244a33cea5601fba to your computer and use it in GitHub Desktop.
Save cezary/332b9739a94abff7244a33cea5601fba to your computer and use it in GitHub Desktop.
const animationFrame = () => new Promise(window.requestAnimationFrame);
const load = (el=window) => new Promise(resolve => el.onload = resolve);
const timeout = (time) => new Promise(resolve => setTimeout(resolve, time))
// https://coderwall.com/p/iygcpa/gameloop-the-correct-way
const animationFrame = () => new Promise(requestAnimationFrame);
const loop = async (draw=function(){}) => {
let lastTimestamp = 0;
let playing = true;
setTimeout(() => playing = false, 20);
while (playing) {
let timestamp = await animationFrame();
let delta = lastTimestamp ? timestamp - lastTimestamp : 0;
draw({ delta, timestamp });
lastTimestamp = timestamp;
}
}
let count = 0;
loop(({ delta, timestamp }) => {
console.log('delta', delta);
console.log('ts', timestamp);
console.log('count', count++);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment