Can someone explain the “debounce” function in Javascript

后端 未结 8 839
旧时难觅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:18

    Simple debounce function :-

    HTML:-

    
    

    Javascript:-

        function debounce(fn, delay) {
          let timeoutID;
          return function(...args){
              if(timeoutID) clearTimeout(timeoutID);
              timeoutID = setTimeout(()=>{
                fn(...args)
              }, delay);
          }
       }
    
    document.getElementById('myid').addEventListener('click', debounce(() => {
      console.log('clicked');
    },2000));
    

提交回复
热议问题