防抖
多次触发事件只会产生一次
function debounce(fn, delay) {
var timer = null;
return function() {
var context = this;
var args = arguments;
if (timer) {
clearTimeout(timer);
timer = null;
};
timer = setTimeout(() => {
fn.apply(context, args);
}, delay);
}
}
节流
单位时间内只会触发一次时间
// 时间戳法
function throttle(fn, delay) {
let preTime = Date.now();
return function() {
let context = this;
let args = arguments;
//这里其实不需要
let nowTime = Date.now();
if (nowTime - preTime >= delay) {
fn.apply(context, args);
preTime = nowTime;
}
}
};
// 定时器法
function throttle(fn, delay) {
let timer = null;
return function() {
let context = this;
let args = arguments;
if (!timer) {
timer = setTimeout(() => {
fn.apply(context, args);
timer = null;
}, delay)
}
}
}
应用场景
防抖
1.搜索联想功能,在输入框不断输入过程中,只会触发最后一次
2.屏幕缩放功能,在调整浏览器窗口的大小时只触发一次
3.自动保存功能
节流
1.多次点击事件,鼠标的多次点击事件在一定时间内只会触发一次
2.监听滚动事件,每过一定时间判断是否达到底部
3.输入联想事件