手寫實現防抖與節流

part1 防抖

<!DOCTYPE html>

<html>
<!-- 防抖 -->
<!-- 防抖就是在n秒內 防止連續觸發,在n秒內觸發了下一次,那就重新計算 -->

<body>
  <div id="content"
    style="height:150px;line-height:150px;text-align:center; color: #fff;background-color:#ccc;font-size:80px;"></div>
  <script>
    let num = 1;
    let content = document.getElementById('content');
    /**
     *非立即執行版
     **/
    function debounceNoAtOnce(func, wait) {
      let timeout;
      return function () {
        let context = this;
        let args = arguments;
        if (timeout) clearTimeout(timeout);
        timeout = setTimeout(() => {
          func.apply(context, args)
        }, wait);
      }
    };

    /**
     *立即執行版
     **/
    function debounceAtOnce(func, wait) {
      let timeout;
      return function () {
        let context = this;
        let args = arguments;
        debugger
        if (timeout) clearTimeout(timeout);

        let callNow = !timeout;
        timeout = setTimeout(() => {
          timeout = null;
        }, wait)

        if (callNow) func.apply(context, args)
      }
    }
    /**
     *聚合版
     **/
    function debounce(func, wait, immediate) {
      let timeout;

      return function () {
        let context = this;
        let args = arguments;

        if (timeout) clearTimeout(timeout);
        if (immediate) {
          var callNow = !timeout;
          timeout = setTimeout(() => {
            timeout = null;
          }, wait)
          if (callNow) func.apply(context, args)
        } else {
          timeout = setTimeout(function () {
            func.apply(context, args)
          }, wait);
        }
      }
    }

    function count() {
      content.innerHTML = num++;
    };
    content.onmousemove = debounce(count, 1000, true);
  </script>
</body>
<script>
</script>

</html>

防抖的目的在於:n秒內點擊多少次都算一次+每次點擊都重新計算時間

應用場景:地圖點擊

 

part2 節流

<!DOCTYPE html>

<html>
<!-- 節流 -->
<!-- 節流是爲了固定的時間段內只能點擊一次 -->

<body>
  <div id="content"
    style="height:150px;line-height:150px;text-align:center; color: #fff;background-color:#ccc;font-size:80px;"></div>
  <script>
    let num = 1;
    let content = document.getElementById('content');
    /**
     *throttleTime 時間戳版
     **/
    throttleTime = function (func, wait) {
      let previde = 0;
      return function () {
        let nowDate = Date.now();
        if (nowDate - previde > wait) {
          func();
          previde = nowDate;
        }
      }
    }
    /**
     *throttleSet 定時器版
     **/
    throttleSet = function (func, wait) {
      let timeout;
      return function () {
        if (!timeout) {
          timeout = setTimeout(() => {
            timeout = false
            func()
          }, wait)
        }
      }
    }

    function count() {
      content.innerHTML = num++;
    };
    content.onmousemove = throttleSet(count, 1000);
  </script>
</body>
<script>
</script>

</html>

節流的目的在於:固定時間段內只能點擊一次

應用場景:輸入框輸入+提交/確定

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