Skip to content

Instantly share code, notes, and snippets.

@windmaomao
Created May 23, 2020 13:44
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 windmaomao/71cd864c3e6aaf1a46e3f32eb3e24c58 to your computer and use it in GitHub Desktop.
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.
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);
}
@windmaomao
Copy link
Author

windmaomao commented May 23, 2020

const animationRate = 30; // 30 ms
const deltaPosition = 0.1;

function animate(deltaP) {
  // Calculate object positions based on deltaP
}

function onFrame() {
  animate(deltaPosition);
}

function startAnimation() {
  setInterval(onFrame, animationRate / 1000);
}

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.

@windmaomao
Copy link
Author

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