Created
March 11, 2018 20:55
-
-
Save siakaramalegos/62f5abccd47fe452f6d9d0e6225975fd to your computer and use it in GitHub Desktop.
Countdown timer component using requestAnimationFrame
This file contains hidden or 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 Timer extends Component { | |
constructor(props) { | |
super(props) | |
// here, getTimeRemaining is a helper function that returns an | |
// object with { total, seconds, minutes, hours, days } | |
this.state = { timeLeft: getTimeRemaining(props.expiresAt) } | |
} | |
// Wait until the component has mounted to start the animation frame | |
componentDidMount() { | |
this.start() | |
} | |
// Clean up by cancelling any animation frame previously scheduled | |
componentWillUnmount() { | |
this.stop() | |
} | |
start = () => { | |
this.frameId = requestAnimationFrame(this.tick) | |
} | |
tick = () => { | |
const timeLeft = getTimeRemaining(this.props.expiresAt) | |
if (timeLeft.total <= 0) { | |
this.stop() | |
// ...any other actions to do on expiration | |
} else { | |
this.setState( | |
{ timeLeft }, | |
() => this.frameId = requestAnimationFrame(this.tick) | |
) | |
} | |
} | |
stop = () => { | |
cancelAnimationFrame(this.frameId) | |
} | |
render() {...} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment