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)
          }
      }
    }

你可能感兴趣的:(前端)