节流函数throttle和防抖函数debounce

  1. 防抖函数:用于控制函数的执行频率,n秒后再执行,一定时间内,只执行最后触发一次,若n秒内重复触发,则重新计时
  2. 应用场景: 输入框输入事件、按钮点击事件、浏览器窗口大小调整事件等,手机号,邮箱等输入验证码
  3. 代码
 function debounce(func, delay) {
 		//定时器id
    let timerId;
    return function (...args) {
      if (timerId) {
        clearTimeout(timerId);
      }
      timerId = setTimeout(() => {
        func.apply(this, args);
      }, delay);
    };
  }
  1. 节流函数,限制函数的执行频率,一段时间内,触发多次,只执行一次
  2. 应用场景,页面滚动,按钮高频点击,游戏技能冷却,搜索框,鼠标移动
  3. 代码
//时间戳方式。可能,最后一次没有被执行
 function throttle(func, wait) {
    let lastTime = 0;
    return function (...args) {
      const now = new Date().getTime();
      if (now - lastTime > wait) {
        fn.apply(this, args);
        lastTime = now;
      }
    };
  }
  //定时器方式
   function throttle(func, wait) {
    let timerId= null;
    return function (...args) {
      if (!timerId) {
	      timerId=setTimeout(()=>{
	      timerId=null;
	        fn.apply(this, args);
      },wait)
      }
    };
  }
  1. 区别:防抖:n秒内,若是重复触发,则重新计时;节流:n秒内,多次触发,只执行一次
  2. 调用,如下
//定义回调函数
function inputChange() {
    console.log("输入值变化");
  }
  //定义输入事件调用函数
  const debounceInput = debounce(inputChange, 2000);
  //模拟输入事件
  setInterval(debounceInput, 1000);

在vue里面使用,参考以下文章
https://blog.youkuaiyun.com/HDdgut/article/details/141157245

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值