Skip to content

Instantly share code, notes, and snippets.

@lucas1richard
Created September 15, 2017 13:50
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 lucas1richard/bcd57ff78cc3d0c0e7fe4689a265deb8 to your computer and use it in GitHub Desktop.
Save lucas1richard/bcd57ff78cc3d0c0e7fe4689a265deb8 to your computer and use it in GitHub Desktop.
/** 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