Skip to content

Instantly share code, notes, and snippets.

@emilyhorsman
Created December 4, 2016 18:30
Show Gist options
  • Save emilyhorsman/cd52af678a9f8cb5eb4abac235f3b318 to your computer and use it in GitHub Desktop.
Save emilyhorsman/cd52af678a9f8cb5eb4abac235f3b318 to your computer and use it in GitHub Desktop.
/* global window */
import React, { Component } from 'react'
import { getDisplayName } from '~/utils'
/**
* Uses requestAnimationFrame to provide the running time of the component.
*/
function withAnimationTime(WrappedComponent) {
class WithAnimationTime extends Component {
constructor(...args) {
super(...args)
this.tick = this.tick.bind(this)
this.state = {
startTime: Date.now(),
time: 0,
skip: false,
}
}
componentDidMount() {
this.requestFrame()
}
componentWillUnmount() {
window.cancelAnimationFrame(this.raf)
}
tick() {
this.setState({
time: (Date.now() - this.state.startTime) / 1000,
})
this.requestFrame()
}
requestFrame() {
this.raf = window.requestAnimationFrame(this.tick)
}
render() {
return (
<WrappedComponent
{...this.props}
time={this.state.time}
/>
)
}
}
WithAnimationTime.displayName = `withAnimationTime(${getDisplayName(WrappedComponent)})`
return WithAnimationTime
}
export default withAnimationTime
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment