防抖节流test

使用场景:onresizescrollmousemove ,mousehover 等

防抖函数如下:连续事件完全触发完成之后,调用一次

    function debounce(fn, waitTime) {
      let timer = null;
      return function() {
        const context = this;
        let args = arguments;
        clearTimeout(timer);
        timer = setTimeout(() => {
          fn.apply(context, args);
        }, waitTime);
      };
    }

节流函数如下:当达到了一定的时间间隔就会执行一次

    function throttle(fn, waitTime) {
      let timer = null;
      return function() {
        const context = this;
        let args = arguments;
        if (!timer) {
          timer = setTimeout(() => {
            fn.apply(context, args);
            clearTimeout(timer);
          }, waitTime);
        }
      };
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章