Skip to content

Instantly share code, notes, and snippets.

@wmcmurray
Last active October 28, 2020 18:09
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 wmcmurray/8819e8356b4bba52dbd2f1b11cc543b2 to your computer and use it in GitHub Desktop.
Save wmcmurray/8819e8356b4bba52dbd2f1b11cc543b2 to your computer and use it in GitHub Desktop.
Ensure consistent frame-rate in a javascript game/app (threejs or anything else).
/**
* Wraps an animation loop function so it can be executed at a specific frame-rate
* loop {Function} = The function you want to execute each frames
* fps {Number} = The desired frame rate
*/
function createFpsCap(loop, fps = 60) {
let targetFps = 0, fpsInterval = 0;
let lastTime = 0, lastOverTime = 0, prevOverTime = 0, deltaTime = 0;
function updateFps(value) {
targetFps = value;
fpsInterval = 1000 / targetFps;
}
updateFps(fps);
return {
// the targeted frame rate
get fps() {
return targetFps;
},
set fps(value) {
updateFps(value);
},
// the frame-capped loop function
loop: function(time) {
deltaTime = time - lastTime;
if(deltaTime < fpsInterval) {
return;
}
prevOverTime = lastOverTime;
lastOverTime = deltaTime % fpsInterval;
lastTime = time - lastOverTime;
deltaTime -= prevOverTime;
return loop(deltaTime);
},
};
}
@wmcmurray
Copy link
Author

@wmcmurray
Copy link
Author

I also made a repository based on this : https://github.com/wmcmurray/game-loop-js for ease of use !

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