Forked from jacob-beltran/requestAnimationFrame.js
Created
December 12, 2018 23:43
-
-
Save HichemBenChaaben/d151daedd7ff48ef5bde13ec93f63917 to your computer and use it in GitHub Desktop.
React Performance: requestAnimationFrame Example
This file contains 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
// 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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment