Posts Simple debounce snippet
Post
Cancel

Simple debounce snippet

The arguments this takes are:

a - A function to be debounced

b - A period of time to wait before debouncing

c - A controller for whether to call the function before or after the timer. If falsey, the function waits for the timer to run down. Otherwise, it gets called first, and then waits to run again until the timer is hit

1
const debounce = (a,b,c) => {var d,e;return function(){function h(){d=null,c||(e=a.apply(f,g))}var f=this,g=arguments;return clearTimeout(d),d=setTimeout(h,b),c&&!d&&(e=a.apply(f,g)),e}};

Usage example in react:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Table extends React.Component {
  constructor(props) {
    super(props);
    this.state = { searchTerm: props.searchTerm };
  }

  setSearchTerm = debounce((searchTerm) => {
    this.setState({ searchTerm });
  }, 1000);

  render() {
    return (
      <div className="widget">
        <p>{this.state.searchTerm}</p>
        <input
          onChange={(e) => {
            this.setSearchTerm(e.target.value);
          }}
        />
      </div>
    );
  }
}

Source / Demo

This post is licensed under CC BY 4.0 by the author.