Skip to content

Instantly share code, notes, and snippets.

@roboshoes
Last active January 25, 2018 18:19
Show Gist options
  • Save roboshoes/cf7ba9b83aca2396dcabb65f49d42249 to your computer and use it in GitHub Desktop.
Save roboshoes/cf7ba9b83aca2396dcabb65f49d42249 to your computer and use it in GitHub Desktop.
Small tweening function for the quick tween.
export function tween( time, update ) {
const start = Date.now();
var isCanceled = false;
var isComplete = false;
var chain = [];
function loop() {
if ( isCanceled ) return;
const difference = Date.now() - start;
const delta = difference / time;
if ( delta >= 1 ) {
isComplete = true;
update( 1 );
chain.forEach( callback => callback() );
} else {
update( delta );
requestAnimationFrame( loop );
}
}
requestAnimationFrame( loop );
return {
cancel() {
isCanceled = true;
},
after( callback ) {
isComplete ? callback() : chain.push( callback );
},
isComplete() {
return isComplete;
}
};
}
@roboshoes
Copy link
Author

This isn't amazingly optimized at all. But it get's the job done in many many use cases I encounter a lot. Obviously no replacement for things like Greensock's GSAP and others.

But these 40 lines (many of which are white space) allow you to:

tween( 1700, t => foo.setFace( t ) ).after( () => some.shenanigans() );

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