Can someone explain the “debounce” function in Javascript

后端 未结 8 926
旧时难觅i
旧时难觅i 2020-11-22 02:57

I am interested in the \"debouncing\" function in javascript, written here : http://davidwalsh.name/javascript-debounce-function

Unfortunately the code is not explai

8条回答
  •  自闭症患者
    2020-11-22 03:13

    This is a variation which always fires the debounced function the first time it is called, with more descriptively named variables:

    function debounce(fn, wait = 1000) {
      let debounced = false;
      let resetDebouncedTimeout = null;
      return function(...args) {
        if (!debounced) {
          debounced = true;
          fn(...args);
          resetDebouncedTimeout = setTimeout(() => {
            debounced = false;
          }, wait);
        } else {
          clearTimeout(resetDebouncedTimeout);
          resetDebouncedTimeout = setTimeout(() => {
            debounced = false;
            fn(...args);
          }, wait);
        }
      }
    };
    

提交回复
热议问题