什么是防抖和节流?如何用 JavaScript 编码实现?

  • 防抖和节流都是一种优化技术,用来降低函数的调用频率,提高性能

防抖(Debouncing)

  • 在连续触发某个事件时,只有当一定时间内没有再次触发时间,才会执行事件处理函数。比如说:我们需要监听用户输入框中的文字,只有用户停止输入一段时间采取发送请求获取数据
    /**
     * 防抖函数
     *
     * @param func 回调函数
     * @param delay 延迟时间
     * @returns {(function(...[*]): void)|*}
     */
    const debounce = (func, delay) => {
        let timeoutId = null
        return function (...arguments) {
            // this
            const context = this;
            // 传递的参数
            const args = arguments;
            // 清除定时器
            timeoutId && clearTimeout(timeoutId);
            // 延迟执行函数
            timeoutId = setTimeout(function () {
                func.apply(context, args);
            }, delay);
        }
    }
  •  使用 防抖函数
    // 调用防抖函数
    const DebounceFn = debounce(function () {
        console.log("debounce我被执行了")
    }, 2000)

    Debounce()

应用场景:

  • 实时搜索
  • 拖拽

节流(Throttling

  • 节流的主要思想是在一系列连续的触发事件中,按照一定的时间间隔执行函数。即,在规定的时间内,无论触发事件多少次,只执行一次函数
    /**
     * 节流函数
     *
     * @param func 回调函数
     * @param delay 延迟时间
     * @returns {(function(...[*]): void)|*}
     */
    function throttling(func, delay) {

        let timeoutId = null

        return function (...arguments) {
          if(!timeoutId){
              // this
              const context = this;
              // 传递的参数
              const args = arguments;

              timeoutId = setTimeout(function (){
                  func.apply(context, args);
                  timeoutId = null
              }, delay)
          }

        }
    }
  •  使用 节流函数
    const ThrottlingFn = throttling(function(){
        console.log("throttling我被执行了")
    }, 2000)

应用场景:

  • 窗口调整
  • 页面滚动
  • 抢购疯狂点击
  • 7
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值