Skip to content

Instantly share code, notes, and snippets.

@PieterScheffers
Forked from jacob-beltran/scroll-monitor.js
Created March 8, 2017 19:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PieterScheffers/5881096cfcb9f91b1584c11c40162829 to your computer and use it in GitHub Desktop.
Save PieterScheffers/5881096cfcb9f91b1584c11c40162829 to your computer and use it in GitHub Desktop.
React Performance: Scroll Monitor Example
class ScrollMonitor extends React.Component {
constructor() {
this.handleScrollStart = this.startWatching.bind( this );
this.handleScrollEnd = debounce(
this.stopWatching.bind( this ),
100,
{ leading: false, trailing: true } );
}
componentDidMount() {
window.addEventListener( 'scroll', this.handleScrollStart );
window.addEventListener( 'scroll', this.handleScrollEnd );
}
componentWillUnmount() {
window.removeEventListener( 'scroll', this.handleScrollStart );
window.removeEventListener( 'scroll', this.handleScrollEnd );
//Make sure the loop doesn't run anymore if component is unmounted
this.stopWatching();
}
// If the watchloop isn't running start it
startWatching() {
if( !this._watchFrame ) {
this.watchLoop();
}
}
// Cancel the next iteration of the watch loop
stopWatching() {
window.cancelAnimationFrame( this._watchFrame );
}
// Keep running on each animation frame untill stopped.
watchLoop() {
this.doThingYouWantToWatchForExampleScrollPositionOrWhatever()
this._watchFrame = window.requestAnimationFrame( this.watchLoop )
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment