Skip to content

Instantly share code, notes, and snippets.

@Sambego
Created May 6, 2016 08:55
Show Gist options
  • Save Sambego/085fa4d1e91b32e5911f63465d37ecd2 to your computer and use it in GitHub Desktop.
Save Sambego/085fa4d1e91b32e5911f63465d37ecd2 to your computer and use it in GitHub Desktop.
Animation function
/*
* A simple function to animate a property of an element to a new value.
*/
const animate = function animate(element, property, value, duration) {
const fps = 60;
const timeout = duration / (1000 / fps);
const startTime = new Date();
const startValue = element[property];
const step = function step() {
const currentTime = new Date();
const passedTime = currentTime.getTime() - startTime.getTime();
const passedTimeRatio = (passedTime / duration) > 1 ? 1 : (passedTime / duration);
const currentValue = (startValue + ((value - startValue) * passedTimeRatio));
element[property] = currentValue;
if (passedTime < duration) {
window.setTimeout(() => {
window.requestAnimationFrame(step);
}, timeout);
}
};
window.requestAnimationFrame(step);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment