Created
April 7, 2018 01:13
-
-
Save idmontie/9c5a8010abac845025b6395a81c3bcca to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SimpleTween extends Component { | |
static defaultProps = { duration: 1000 } | |
constructor(props) { | |
super(props); | |
this.state = { | |
timeStart: +new Date(), | |
current: props.start, | |
}; | |
this.calculate = this._calculate.bind(this); | |
} | |
componentDidMount() { | |
this.timer = setInterval(this.calculate, 1000 / 60); | |
} | |
componentWillUnmount() { | |
if (this.timer) { | |
clearInterval(this.timer); | |
} | |
} | |
_calculate() { | |
const { duration, start, end } = this.props; | |
const { timeStart } = this.state; | |
const time = +new Date() - timeStart; | |
if (time > duration) { | |
this.setState(() => ({ | |
current: end, | |
})); | |
return; | |
} | |
const currentPosition = linear(time, start, end - start, duration); | |
this.setState(() => ({ | |
current: currentPosition, | |
})); | |
} | |
render() { | |
const { children } = this.props; | |
const { current } = this.state; | |
return children({ current }); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment