防抖
类比送外卖: 如果 5s 内没有新单,则去送当前手中积压的单子,如果接到新单,则再等 5s
/*
函数防抖 —— 送外卖
*/
const fn = function () {
console.log(111)
}
let timeID = null
button.onClick = function () {
if(timeID) {
timeID = null
}
timeID = setTimeout(() => {
fn()
timeID = null
}, 5000)
}
封装一下:
const debounce = (fun, time) => {
let timer = null;
return (...args) => {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fun.call(undefined, ...args);
timer = null;
}, time)
}
}
const testFun1 = debounce(fn, 3000);
节流
类比游戏技能冷却,5s 内只能触发一次
const fn = function () {}
let CD = false
button.onClick = function () {
if(CD) {
return
} else {
fn()
CD = true
setTimeout(() => {
CD = false
}, 5000)
}
}
封装一下:
const fn = function () {
console.log()
}
const throttle = (fun, time) => {
let CD = false
let timer = null;
return (...args) => {
if (CD) return;
fn(...args);
CD = true;
timer = setTimeout(() => {
CD = false;
}, time)
}
}
const testFun = throttle(fn, 5 * 1000);
testFun(1, 3);