Created
May 23, 2020 13:44
-
-
Save windmaomao/71cd864c3e6aaf1a46e3f32eb3e24c58 to your computer and use it in GitHub Desktop.
In doing so, we guarantee that the animation time is independent of how often the timer callback is actually executed. If there are big delays (due to other blocking events), this method may result in dropped frames.
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
const animationRate = 30; // 30 ms | |
let initialTime, elapsedTime; | |
function animate(deltaT) { | |
// calculate object positions based on deltaT | |
} | |
function onFrame() { | |
const currentTime = new Date().getTime(); | |
elapsedTime = currentTime - initialTime; | |
if (elapsedTime < animationRate) return; // come back later | |
animate(elapsedTime); | |
initialTime = currentTime; | |
} | |
function startAnimation() { | |
setInterval(onFrame, animationRate / 1000); | |
} |
const animationRate = 30; // 30 ms
const deltaPosition = 0.1;
let initialTime, elapsedTime;
function animate(delta) {
// Calculate object positions based on delta
}
function onFrame() {
const currentTime = new Date().getTime();
elapsedTime = currentTime - initialTime;
if (elapsedTime < animationRate) return; // come back later!
let steps = Math.floor(elapsedTime / animationRate);
while (steps > 0) {
animate(deltaPosition);
steps -= 1;
}
initialTime = currentTime;
}
function startAnimation() {
initialTime = new Date().getTime();
setInterval(onFrame, animationRate / 1000);
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This may lead to frozen frames that occur when there is a long list of blocking events because the object's positions would not be updated in a timely manner.