节流
节流是指在一个函数执行后的指定时间内,该函数不再被执行。(类似技能冷却,技能使用后有冷却时间,冷却时间结束后才能被再次使用)
// 节流 throttle
/**
* 1、滚动加载
* 2、高频点击
*/
const throttle = (fn, time) => {
let flag = false, timer = null;
return (...args) => {
if (flag) {return}
fn.call(undefined, ...args);
flag = true;
timer = setTimeout(() => {
flag = false;
}, time);
}
}
// 实现 this 版本, 即多传一个参数
const throttle = (fn, time, asThis) => {
let flag = false, timer = null;
return (...args) => {
if (flag) {return}
fn.call(asThis, ...args);
flag = true;
timer = setTimeout(() => {
flag = false;
}, time);
}
}
防抖
防抖是指一个函数在指定的时间后执行,在此期间,如果再次调用该函数,则重置该时间。(类似回城被打断,回城被打断后,只能重新读秒回城)
// 防抖 debounce
/**
* 1、拖动窗口大小时,只在窗口调整完成后,再计算窗口大小,防止重复渲染
* 2、搜索框搜索输入,在最后一次输入完,再发送请求
*/
const debounce = (fn, time) => {
let timer = null;
return (...args) => {
if (timer) {
clearTimeout(timer);
};
timer = setTimeout(() => {
fn.call(undefined, ...args);
timer = null;
}, time);
}
}
// 实现 this 版本, 即多传一个参数
const debounce = (fn, time, asThis) => {
let timer = null;
return (...args) => {
if (timer) {
clearTimeout(timer);
};
timer = setTimeout(() => {
fn.call(asThis, ...args);
timer = null;
}, time);
}
}