总结:
防抖:单位时间内,频繁触发事件,只执行最后一次;
典型场景:搜索框搜索输入;
代码思路:利用定时器,每次触发先清掉以前的定时器(从新开始)
节流:单位时间内,频繁触发事件,只执行一次;
典型场景:高频事件、快速点击、鼠标滑动、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;