防抖 - debounce
原理: 将多个函数调用合成为一个函数,并在设置一定的时间后仅被调用一次。
应用:搜索框等待用户输入完成后,延迟一定时间在进行搜索功能。
代码实现
function debounce(fn, delay) {
// 维护一个 timer,用来记录当前执行函数状态
let timer = null;
return function() {
// 通过 ‘this’ 和 ‘arguments’ 获取函数的作用域和变量
let context = this;
let args = arguments;
// 清理掉正在执行的函数,并重新计算时间
clearTimeout(timer);
timer = setTimeout(function() {
fn.apply(context, args);
}, delay);
}
}
节流 - throttle
原理: 节流函数不管事件触发有多频繁,都会保证在规定时间内一定会执行一次真正的事件处理函数。
应用:搜索框每隔一定时间给与用户输入输入提示。
代码实现有两种,一种是时间戳,另一种是定时器
(1) 时间戳(每次执行后刷新开始时间戳,通过 调用时间戳 与 上一次执行时间戳 求差 在 规定时间内进行控制函数调用)
function throttle(func, delay){
let prev = Date.now();
return function(){
const context = this;
const args = arguments;
const now = Date.now();
if(now - prev >= delay){
func.apply(context, args);
prev = Date.now();
}
}
}
(2)定时器(每次执行时都新建定时间对象控制 函数调用)
fucntion throttle(func, delay){
let timer = null;
return funtion(){
let context = this;
let args = arguments;
if(!timer){
timer = setTimeout(function(){
func.apply(context, args);
timer = null;
}, delay);
}
}
}