Created
September 15, 2017 13:50
-
-
Save lucas1richard/bcd57ff78cc3d0c0e7fe4689a265deb8 to your computer and use it in GitHub Desktop.
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
/** When the function returned by debounce is executed multiple times before a specified time, | |
* the function passed into debounce is not executed. It is only executed if the time elapsed is greater than specified. | |
* @param {function} fn - the function to be debounced | |
* @param {number} time - the time in ms before executing fn | |
*/ | |
const debounce = (fn, time) => { | |
let timer; | |
return function() { | |
clearTimeout(timer); | |
timer = setTimeout(() => fn.apply(fn, arguments), time); | |
}; | |
}; | |
// Use in React | |
import React from 'react'; | |
class Comp extends React.Component { | |
constructor() { | |
super(); | |
// First bind it, then debounce it | |
this.someFunction = this.someFunction.bind(this); | |
this.someFunction = debounce(this.someFunction, 700); | |
} | |
someFunction() { | |
} | |
render() { | |
<input onChange={this.someFunction} /> | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment