Skip to content

Instantly share code, notes, and snippets.

@bericp1
Forked from jacob-beltran/scroll-monitor.js
Created April 24, 2017 01:30
Show Gist options
  • Save bericp1/be28027b44a228d467e0e37de8a7bf7b to your computer and use it in GitHub Desktop.
Save bericp1/be28027b44a228d467e0e37de8a7bf7b 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