防抖函数
- 如果下达命令后,在t毫秒内再次下达该命令,则取消刚刚下达的命令,只执行新命令
- 最终效果: 对于连续动作(动作间的时间间隔小于t),以最后一次为准
function doubunce (fn, delay) {
let timer = null;
return function () {
const self = this;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(self, argments)
}, delay)
}
}
应用场景:
- 搜索框搜索输入。只需用户最后一次输入完,再发送请求
- 手机号、邮箱验证输入检测
- 窗口大小Resize。只需窗口调整完成后,计算窗口大小。防止重复渲染。
节流函数
- 从上一次命令结束开始的一定时间范围t内,如果多次连续下达命令,则只执行当前时间段t内第一次命令。
- 最终效果:对于连续动作,会过滤出部分动作,让这些过滤后的动作之间的执行间隔大于等于t
- 时间戳版本
function throttle () {
let pre = 0;
return function () {
const self = this;
const now = Date.now();
if (now - pre > delay) {
setTimeout(function () {
fn.apply(self, argments)
pre = Date.now();
}, delay);
}
}
}
function throttle (fn, delay) {
let timer = null;
return function () {
const self = this
if (!timer) {
setTimeout(function () {
fn.apply(self, argments);
timer = null;
}, delay)
}
}
}
应用场景:
- 滚动加载,加载更多或滚到底部监听
- 高频点击提交,表单重复提交