Skip to content

Instantly share code, notes, and snippets.

@jacob-beltran
Last active April 17, 2020 04:05
Show Gist options
  • Save jacob-beltran/aa114af1b6fd5de866aa365e3763a90b to your computer and use it in GitHub Desktop.
Save jacob-beltran/aa114af1b6fd5de866aa365e3763a90b to your computer and use it in GitHub Desktop.
React Performance: requestAnimationFrame Example
// How to ensure that our animation loop ends on component unount
componentDidMount() {
this.startLoop();
}
componentWillUnmount() {
this.stopLoop();
}
startLoop() {
if( !this._frameId ) {
this._frameId = window.requestAnimationFrame( this.loop );
}
}
loop() {
// perform loop work here
this.theoreticalComponentAnimationFunction()
// Set up next iteration of the loop
this.frameId = window.requestAnimationFrame( this.loop )
}
stopLoop() {
window.cancelAnimationFrame( this._frameId );
// Note: no need to worry if the loop has already been cancelled
// cancelAnimationFrame() won't throw an error
}
@iamdanthedev
Copy link

Thanks man!

@iamdanthedev
Copy link

Should be this._frameId on 22

@Mikou
Copy link

Mikou commented Jul 20, 2018

componentDidMount() {
this.startLoop();
}

componentWillUnmount() {
this.stopLoop();
}

startLoop() {
if (!this._frameId) {
this._frameId = window.requestAnimationFrame(this.loop.bind(this));
}
}

loop() {
// perform loop work here
// Set up next iteration of the loop
this._frameId = window.requestAnimationFrame(this.loop.bind(this));
}

stopLoop() {
window.cancelAnimationFrame(this._frameId);
// Note: no need to worry if the loop has already been cancelled
// cancelAnimationFrame() won't throw an error
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment