函数 防抖和节流

1、防抖

当持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次,如果设定的时间到来之前,又一次触发了事件,就重新开始延时。

代码:

以闭包的形式返回一个函数,内部解决了this指向的问题,event对象传递的问题

/**
 * 防抖
 * @param {*} fn  执行函数
 * @param {*} delay  防抖间隔时间
 */
const debounce = function (fn, delay = 500) {
  let timer = null
  return function () {
    let content = this;
    let args = arguments;
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fn.apply(content, args)
    }, delay)
  }
}

const thrDeb = {
  debounce
};

export default thrDeb;

2、节流

当持续触发事件时,保证一定时间段内只触发一次事件处理函数

代码:

以闭包的形式返回一个函数,内部解决了this指向的问题,event对象传递的问题

/**
 * 节流
 * @param {*} fn  执行函数
 * @param {*} delay  节流间隔时间
 */
const throttle = function (fn, delay = 500) {
  let timer = null
  return function() {
    if (timer) {
      return
    }
    let content = this;
    let args = arguments;
    timer = setTimeout(() => {
      timer = null
    }, delay)
    fn.apply(content, args)
  }
}

const thrDeb = {
  throttle
};

export default thrDeb;

使用方法:

在utils文件夹内创建thrDeb文件,将防抖、节流函数用export抛出

<div @click="getThrottle">节流</div>

methods: {
	getThrottle: utils.thrDeb.throttle(function () {
      console.log("使用了节流函数!");
    }, 1500)
}

总结

防抖:原理是维护一个定时器,将很多个相同的操作合并成一个。规定在delay后触发函数,如果在此之前触发函数,则取消之前的计时重新计时,只有最后一次操作能被触发。

节流:原理是判断是否达到一定的事件来触发事件。某个时间段内只能触发一次函数。

区别:防抖只会在最后一次事件后执行触发的函数,节流不管事件多么频繁,都会保证在规定时间段内触发事件函数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值