防抖和节流的区别以及代码实现

330 阅读2分钟

1、区别

防抖和节流的目的都是为了节省性能损耗。都是希望在一定的时间间隔内,不要重复触发请求。一般场景用在搜索和网页滚动事件中。他们的区别如下:

  • 防抖:在规定时间内执行函数。如果在这段时间内再次触发,则重新开始计时。
  • 节流: 在固定的时间执行函数。如果在这段时间内再次触发,不会重新开始计时。在这段时间只能执行一次。

通俗一点讲,防抖就比如说你准备学习60分钟,如果在此期间,你被外界因素打断了,你就重新开始学习60分钟。
                  8c5dc2e8d6b9bd0acbe4a700bc94fe7.jpg
节流就比如说你准备学习60分钟,如果在此期间,你被外界因素打断了,不管什么事你都置之不理,先把60分钟学习完。

2.代码实现

    /**
     * @description: 防抖函数
     * @param {function} func 回调函数
     * @param {function} delay 间隔时间
     * @return: function
     */    
    function antiShake(func, delay) {
      let timer // 通过闭包的方式保存timer的值
      return function (...args) { 
       // 如果之前已经进入过了,timer就已经存在,清空定时器
        if (timer) { 
          clearTimeout(timer)
        }
       // 重新设置定时器  注:这是一次性定时器
        timer = setTimeout(() => {
          func.apply(this, args)
        }, delay);
      }
    }


    /**
     * @description: 节流函数
     * @param {function} func 回调函数
     * @param {function} wait 间隔时间
     * @return: function
     */    
    function throttling(func, wait) {
      let timer // 通过闭包的方式保存timer的值
      return function(...args) { 
        // 如果定时器已经存在  要等定时时间执行完才能重新执行
        if (!timer) {
          timer = setTimeout(() => {
            func.apply(this, args)
            timer = null 
          }, wait);
        }
      }
    }
    // 插入一个Input文本框  监听输入事件
    document.querySelector('input').addEventListener('keyup', antiShake(function() 	 {
      console.log('只要你点的够快,我就不执行')
    }, 500))
    // 监听鼠标在界面移动
    document.querySelector('html').addEventListener('mousemove', throttling(function() {
      console.log('1s只能执行一次')
    }, 1000))

仅仅是个人理解,如有不足之处,敬请指正。