防抖节流

防抖(debounce):所谓防抖,就是指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。

节流(throttle):所谓节流,就是指连续触发事件但是在 n 秒中只执行一次函数。节流会稀释函数的执行频率。

 防抖在于控制次数,节流在于控制频率!

<!DOCTYPE html>

<body>
  <div id="content"></div>
</body>

<style>
  #content {
    width: 500px;
    height: 200px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #ccc;
    margin: 200px auto;
    font-size: 28px;
  }
</style>
<script>
  let num = 1;
  let content = document.getElementById("content")

  function count() {
    content.innerHTML = num++;
  }

  //防抖 immediate true 表立即执行,false 表非立即执行
  function debounce(fn, wait, immediate) {
    let timer;
    return function () {
      let _self = this;
      let args = arguments;
      if (timer) clearTimeout(timer);
      if (immediate) {
        let callNow = !timer;
        timer = setTimeout(() => {
          timer = null;
        }, wait);
        if (callNow) fn.apply(_self, args)
      } else {
        timer = setTimeout(() => {
          fn.apply(_self, args)
        }, wait)
      }

    }
  }
  //节流 type为1是时间戳比较  type为2是定时器
  function throttle(fn, wait, type) {
    if (type == 1) {
      var c = 0;
    } else {
      var timer;
    }
    return function () {
      let _self = this;
      let args = arguments;
      if (type == 1) {
        let now = Date.now();
        if (now - c > wait) {
          fn.apply(_self, args)
          c = now;
        }
      } else {
        if (!timer) {
          timer = setTimeout(() => {
            timer = null;
            fn.apply(_self, args)
          }, wait)
        }
      }
    }
  }

  content.onmousemove = throttle(count, 1000, 2)


</script>

 

posted @ 2020-05-15 14:44  骑驴追火箭啊  阅读(159)  评论(0编辑  收藏  举报