Skip to content

Instantly share code, notes, and snippets.

@anish000kumar
Last active June 3, 2021 11:51
Show Gist options
  • Save anish000kumar/2ca0ec7de78502a04790e2cb83dc74f0 to your computer and use it in GitHub Desktop.
Save anish000kumar/2ca0ec7de78502a04790e2cb83dc74f0 to your computer and use it in GitHub Desktop.
Animation loop
function animate({ timing, duration, draw }){
return new Promise((resolve, reject) => {
const start = performance.now();
function animation(time){
const progress = Math.min((time-start)/duration, 1);
const visualProgress = timing ? timing(progress): progress;
draw(visualProgress);
if(progress < 1) requestAnimationFrame(animation)
else resolve()
}
requestAnimationFrame(animation)
})
}
// USAGE examples
const el = document.getElementsByTagName('div')[0]
const toRight = {
duration: 1000,
draw(progress){
el.style.transform = `translateX(${300*progress}px)`
}
};
const toLeft = {
duration: 1000,
draw(progress){
el.style.transform = `translateX(${300 - 300*progress}px)`
}
};
animate(toRight)
.then(() => animate(toLeft))
.then(() => animate(toRight))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment