Skip to content

Instantly share code, notes, and snippets.

@peeke
Last active March 17, 2019 19:58
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 peeke/67cd617a206b36c0d0dff70681f53d8d to your computer and use it in GitHub Desktop.
Save peeke/67cd617a206b36c0d0dff70681f53d8d to your computer and use it in GitHub Desktop.
Easily animate an arbitrary property
const noop = () => {}
const animate = function(options = {}) {
const defaultOptions = { from: 0, to: 1, duration: 1000, callback: noop, ease: t => t }
const { from, to, duration, callback, ease } = {...defaultOptions, ...options}
const delta = to - from
let start
return new Promise(resolve => {
const tick = time => {
if (!start) start = time
const progress = (time - start) / duration
if (progress >= 1) {
callback(to)
resolve()
return
}
callback(from + ease(progress * delta))
window.requestAnimationFrame(tick)
}
window.requestAnimationFrame(tick)
})
}
export default animate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment