Skip to content

Instantly share code, notes, and snippets.

@davidhellsing
Last active February 20, 2019 13:38
Show Gist options
  • Save davidhellsing/6d5d8fd1a62943e43a6a91f6982e63b8 to your computer and use it in GitHub Desktop.
Save davidhellsing/6d5d8fd1a62943e43a6a91f6982e63b8 to your computer and use it in GitHub Desktop.
Simple, functional animation of values using React Native Easing
import { Easing } from 'react-native'
/*
* Function that animates a value from 0 - 1
* Uses React Native’s Easing functions
* Returns an object that has a stop() function
*/
interface Args {
duration: number,
easing?: (value: number) => number,
onFrame?: (value: number) => void,
onComplete?: () => void,
}
export type AnimationReturnType = {
stop: () => void,
}
export default ({
duration = 800,
easing = Easing.inOut(Easing.quad),
onFrame,
onComplete
}: Args) => {
let stopped = false
const returnObject: AnimationReturnType = {
stop: () => {
stopped = true
},
}
const then = Date.now()
function loop() {
if (!stopped) {
const time = Date.now() - then
if (time > duration) {
if (onComplete) {
onComplete()
}
} else if (onFrame) {
onFrame(easing(time / duration))
requestAnimationFrame(loop)
}
}
}
loop()
return returnObject
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment