节流
节流就是针对调用频率高的函数设置冷却时间,防止过于频繁的调用引起的浏览器性能问题以及ajax调用问题。
const throttle = (fn,time) =>{
let cooldown = false;
return (...args) =>{
if (cooldown) return;
fn.call(undefined,...args);
cooldown = true;
setTimeout(()=>{cooldown = false},time);
}
}
//使用方式
const f2 = throttle(()=>console.log(1), 3000) //设置cd为3秒
f2() //第一次调用,打印出1,进入冷却
f2()//第二次在3秒内调用,没有打印出1
防抖
在事件被触发n秒后再执行回调函数,如果在这n秒内又被触发,则重新计时。(类似LOL这类游戏里面的回城)
const debounce = (fn,time)=>{
let timer = null;
return (...args)=>{
if (timer) clearTimeout(timer);
timer = setTimeout(()=>{
fn.call(undefined,...args);
timer = null},time)
}
}
//使用方式
const f2 = debounce(()=>console.log(1), 3000) //设置时间为3秒
f2()//第一次执行
f2()//3秒内第二次执行,在这次之后等待3秒输出 1