Last active
November 6, 2018 15:16
-
-
Save BiosBoy/c0b6fd5d554f3f2eac7d326a05b75708 to your computer and use it in GitHub Desktop.
Quick and dirty Debounce and Throttle decorators for React Components
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 App extends PureComponent<IProps, any> { | |
constructor(props: IProps) { | |
super(props) | |
this.state = { | |
isThrottled: false, | |
savedArgs: null, | |
timer: null | |
} | |
} | |
_debounce = (func, ms) => { | |
const { timer } = this.state | |
const resolveEvent = () => { | |
func() | |
this.setState({ | |
timer: null | |
}) | |
} | |
if (timer) { | |
clearTimeout(timer) | |
} | |
const localTimer = setTimeout(resolveEvent, ms) | |
this.setState({ | |
timer: localTimer | |
}) | |
} | |
_throttle = (...args) => { | |
const { isThrottled, savedArgs } = this.state | |
const [func, ms] = args | |
const saveArgs = contextArgs => { | |
this.setState({ | |
savedArgs: contextArgs | |
}) | |
} | |
const saveThrottle = status => { | |
this.setState({ | |
isThrottled: status | |
}) | |
} | |
const resolveEvent = () => { | |
saveThrottle(false) | |
if (savedArgs) { | |
this._throttle(func, ms) | |
saveArgs(null) | |
} | |
} | |
if (isThrottled) { | |
saveArgs(args) | |
return | |
} | |
func() | |
saveThrottle(true) | |
setTimeout(resolveEvent, ms) | |
} | |
_handleClick = () => { | |
const { onClick } = this.props | |
this._debounce(onClick, 1000) // debounce | |
// ...or... | |
this._throttle(onClick, 1000) // throttle | |
} | |
render() { | |
// ...some UI | |
} | |
} | |
export default App |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment