Home debounce
Post
Cancel

debounce

debounce

what is debounce

  • A debounce function in JavaScript ensures that your code is executed only once per user input. It is commonly used for scenarios such as search box suggestions, text-field auto-saves, thereby enhancing user experience and optimizing performance.

how debounce works,check the link

  • The principle of debounce is to wait for a certain period of time (the delay period) after the function is triggered. If the function is triggered again during this delay period, the timer is reset, and the function will only be executed when there are no further triggers within the delay period. This prevents the function from being executed multiple times in a short period, and it is commonly used in scenarios like search box suggestions or form validation, where we want the function to be executed only after the user stops inputting or interacting.
1
2
3
4
5
6
7
8
9
10
11
function debounce<T extends any[]>(cb: Function, delay: number) {
  let timer: NodeJS.Timeout;
  return (...arg: T) => {
    clearTimeout(timer);
    timer = setTimeout(() => {
      cb(...arg);
    }, delay);
  };
}

const debouncedClickHandler = useCallback(debounce(handleClick, 1000), []);
  • Please Note, that the handleClick function should be the previous handleClick function that bind to the onClick event.

  • we probably noticed that on the example provide, the button’s onClick event is not called until the timer countdown is over, which means that the user who clicked the button will have to wait for a while before the onClick event to work, which is not very good, as we want to bring better user experience and will not let user wait for no reason(get them the result before they click the button that is my motto).
  • in order to do that, we need to modify our code a bit to make it throttle instead of debounce.

  • here is the code:
1
2
3
4
5
6
7
8
9
10
11
12
const throttle = <T extends any[]>(cb: Function, delay: number) => {
  let timer: NodeJS.Timeout | undefined;
  return (...arg: T) => {
    if (!timer) {
      cb(...arg);
    }
    clearTimeout(timer);
    timer = setTimeout(() => {
      timer = undefined;
    }, delay);
  };
};
  • this code will introduce a timer, when timer starts, cb will be triggered when the timer id is not available, i.e. when timer hasn’t start or when timer is over. in another word, when the throttle function is called for the first time, cb will be triggered, and then a timer will also started with a timer id called timer. with the timer id, cb will not work because of ` if (!timer) condition check and when the timer is over, this timer id will be set to be undefined so that allow the cb` callback function to work again.
This post is licensed under CC BY 4.0 by the author.