防抖(debounce)
原理
事件响应函数fn在一段时间后才执行,如果在这段内再时间再次调用,则重新计算执行时间,当预定的时间内没有再次调用该函数,则执行fn
实现
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)
}
}
注意细节
- 函数中this的指向问题
- 函数的参数如何获取
应用场景
- scroll事件滚动出发
- 搜索框输入查询
- 表单验证
- 按钮提交事件
- 浏览器窗口缩放等等
节流(throttle)
原理
频繁触发函数fn,每间隔一段时间执行函数fn
实现
- 时间戳的方式实现
function throttle(func, time) { let _this, args, let initialTime = 0; return function() { _this = this; args = arguments; let currrentTime = new Date().getTime(); if(currrentTime - initialTime > time){ func.apply(_this, arguments); initialTime = currrentTime } } } - 通过定时器的方式实现
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元素的拖拽
- 射击游戏
- 计算鼠标移动的距离
- 监听滚动条滚动事件