概念:
防抖(debounce):事件响应函数fn在一段时间后才执行,如果在这段内再时间再次调用,则重新计算执行时间,当预定的时间内没有再次调用该函数,则执行fn
节流(throttle): 频繁触发函数fn,每间隔一段时间执行函数fn 。节流函数的作用是规定一个单位时间,在这个单位时间内最多只能触发一次函数执行,如果这个单位时间内多次触发函数,只能有一次生效。
- debounce(防抖)的特点是当事件快速连续不断触发时,动作只会执行一次
- 节流(throttle)函数不管事件触发有多频繁,每隔一个时间周期就会执行一次事件处理程序
1, 节流
比如公交车站等车,每经过30分钟就会发车,不管后面还有没有人都会发车。这就是节流的过程。
2, 防抖
以最后一个乘客为准,再等30分钟,如果30分钟内都没有人上车,就会发车。如果在期间有人上车,那么重新等30分钟。这就是防抖的过程
简单函数实现防抖
function debounce (func, wait) {
let timer = null;
return function() {
let _this = this;
let args = arguments;
if (timer) {
clearTimeout(timer)
timer = null
}
timer = setTimeout(function () {
func.call(_this, ...args);
}, wait)
}
}
注意细节:
1, 函数中this的指向问题
2, 函数的参数如何获取
应用场景
- scroll事件滚动出发
- 搜索框输入查询
- 表单验证
- 按钮提交事件
- 浏览器窗口缩放等等
简单函数实现节流
function throttle(func, time) {
let _this;
let args;
let timer = null;
return function() {
_this = this;
args = arguments;
if(!timer) {
timer = null;
timer = setTimeout(() => {
func.call(_this, ...args)
}, time)
}
}
}
应用场景
- Dom元素的拖拽
- 射击游戏
- 计算鼠标移动的距离
- 监听滚动条滚动事件