节流(规定时间内执行一次,相当于技能冷却)
const throttle = (fn, timer) => {
let time = null;
return (...args) => {
console.log(time)
if (time !== null) {
return;
}
fn.call(undefined, ...args);
time = setTimeout(() => {
time = null;
}, timer);
};
};
// 使用
const f = throttle(()=>{console.log('hi')}, 3000)
f() //打印hi
f() // 冷却中
防抖(一段时间内多次操作只执行最后一次操作)
const debounce = (fn,time)=>{
let timeId = null
return (...args)=>{
if(timeId !==null){
clearTimeout(timeId)
}
timeId=setTimeout(()=>{
fn.call(undefined,...args)
timeId = null
},time)
}
}
节流与防抖的作用都是防止函数多次调用。区别在于,节流只会在规定的时间内调用一次,而防抖会调用多次,但只会输出最后一次的触发结果