一、函数防抖(debounce)
防抖函数:一个需要频繁触发的函数,在规定时间内,只让最后一次生效,前面的不生效。
// 函数防抖
const debounce = (fn, delay = 300) => {
let timer = null;
return function () {
const args = arguments;
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
};
二、函数节流(throttle)
函数节流:一个函数执行一次后,只有大于设定的执行周期后才会执行第二次。
有个需要频繁触发函数,出于优化性能角度,在规定时间内,只让函数触发的第一次生效,后面不生效。
// 函数节流
const throttle = (fn, delay = 500) => {
let timer = null;
return function () {
const args = arguments;
if (timer) return;
timer = setTimeout(() => {
fn.apply(this, args);
timer = null;
}, delay);
};
};
452

被折叠的 条评论
为什么被折叠?



