一、防抖
n秒后才执行,如果上一次触发和本次触发时间间隔小于n,重新计时。比如搜索框输入、窗口调整大小。
function debounce(fn, delay) {
let timer = null;
return function() {
const context = this;
const args = arguments;
if (timer) clearTimeout(timer);
timer = setTimeout(function() {
fn.apply(context, args);
}, delay);
}
}
//注意两个问题
//参数传递问题:原始防抖函数fn的参数没有传递给setTimeout中的回调函数。应该将参数传递给fn,以确保正确执行被防抖的函数。
//上下文丢失问题:返回的函数中没有正确设置执行上下文(this)。如果原始防抖函数依赖于特定的执行上下文,那么这个函数可能无法按预期工作。
二、节流
n秒内只运行一次,若在n秒内被重复触发,只有一次生效,这里添加了一个参数,实现立即执行。比如搜索联想、滚动加载、加载更多 。
function throttle(fn, delay) {
let timer = null;
let shouldExecute = true;
return function() {
const context = this;
const args = arguments;
if (shouldExecute) {
fn.apply(context, args);
shouldExecute = false;
timer = setTimeout(() => {
shouldExecute = true;
timer = null;
}, delay);
}
};
}