防抖和节流

总结:
防抖:单位时间内,频繁触发事件,只执行最后一次;
典型场景:搜索框搜索输入;
代码思路:利用定时器,每次触发先清掉以前的定时器(从新开始)
节流:单位时间内,频繁触发事件,只执行一次;
典型场景:高频事件、快速点击、鼠标滑动、resize事件、scroll事件
代码思路:利用定时器,等定时器执行完毕,才开启定时器(不要打断)
lodash的debounce(防抖)和throttle(节流)

impor _ from 'lodash';
this.onsearch = _.debounce(this.onsearch, 1000)
this.onThrottle = _.throttle(this.onThrottle, 2000)

防抖
函数防抖(debounce)就是指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。
简单的说,当一个动作连续触发,则只执行最后一次。

使用场景:搜索框调接口搜索—模糊搜索

function debounce(func, wait) {  
    let timeout;  
    return  function() {  
        let context = this;  
        let args = arguments;  
        if (timeout) clearTimeout(timeout);  
        timeout = setTimeout(() => {  
            func.apply(context, args);  
        }, wait);  
    };  
}  
// 使用  
window.onscroll = debounce(function() {  
    console.log('debounce');  
}, 1000);

节流
应用场景:
1、DOM 元素的拖拽功能实现(mousemove)
2、射击游戏的 mousedown/keydown 事件(单位时间只能发射一颗子弹),技能 CD
3、计算鼠标移动的距离(mousemove)
4、Canvas 模拟画板功能(mousemove)
5、搜索联想功能(keyup)
6、滚动加载,加载更多或滚到底部监听
7、就像每 200ms 监测滚动位置来触发 css 动画。

	// 节流
	 function throttle(fn, delay) {
	            var prevTime = Date.now();
	            return function () {
	                var curTime = Date.now();
	                if (curTime - prevTime > delay) {
	                    fn.apply(this, arguments);
	                    prevTime = curTime;
	                }
	            };
        }
    
      // 使用  
       var throtteScroll = throttle(function () {
           console.log('throtte');
       }, 3000);
       window.onscroll = throtteScroll;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值