Skip to content

Instantly share code, notes, and snippets.

@idmontie
Created April 7, 2018 01:13
Show Gist options
  • Save idmontie/9c5a8010abac845025b6395a81c3bcca to your computer and use it in GitHub Desktop.
Save idmontie/9c5a8010abac845025b6395a81c3bcca to your computer and use it in GitHub Desktop.
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