乐趣区

关于前端:1-防抖节流

防抖

  • 事件被执行 n 秒后,再执行回调,如果 n 秒内又触发了,则从新计时

    function debounce(fn, delay) {
      let timer = null;
      return function(){cleatTimeout(timer);
          const self = this;
          const args = arguments;
          timer = setTimeout(() => {fn.apply(self, args);
          }, delay)
      }
    }

节流

  • 每隔一段时间,执行一次

    function throttled(fn, delay) {const startTime = Date.now();
      let timer = null;
      return function(){
          const self = this;
          const args = arguments;
          clearTimeout(timer);
          let currentTime = Date.now();
          const remaining = delay - (currentTime - startTime);
          if(remaining < 0) {fn.apply(self, args);
              currentTime = Date.now();}else {timer = setTimeout(fn, delay)
          }
      }
    }
退出移动版