Skip to content

Instantly share code, notes, and snippets.

@idmontie
Created April 7, 2018 02:33
Show Gist options
  • Save idmontie/a54d36922d7c008901a9de7ef0ff023f to your computer and use it in GitHub Desktop.
Save idmontie/a54d36922d7c008901a9de7ef0ff023f to your computer and use it in GitHub Desktop.
class Tween extends Component {
static defaultProps = {
duration: 1000,
}
constructor(props) {
super(props);
this.state = {
timeStart: +new Date(),
start: props.defaultStart || 0,
current: props.defaultStart || 0,
};
this.calculate = this._calculate.bind(this);
}
componentDidMount() {
this.timer = setInterval(this.calculate, 1000 / 60);
}
componentWillUnmount() {
if (this.timer) {
clearInterval(this.timer);
}
}
componentWillReceiveProps(nextProps) {
if (nextProps.end !== this.props.end) {
this.setState((state) => ({
timeStart: +new Date(),
start: state.current,
}));
}
}
_calculate() {
const { func, duration, end } = this.props;
const { timeStart, start } = this.state;
const time = +new Date() - timeStart;
if (time > duration) {
this.setState(() => ({
current: end,
}));
return;
}
const currentPosition = func(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