functiondebounce(fn, t){let delay = t ||500;//创建一个标记用来存放定时器的返回值let time =null;return(...args)=>{// 每当用户输入的时候把前一个 setTimeout clear 掉 if(time)clearTimeout(time);// 然后又创建一个新的 setTimeout, 这样就能保证输入字符后的 interval 间隔内如果还有字符输入的话,就不会执行 fn 函数
time =setTimeout(()=>{fn.call(this, args);}, delay)}}//处理函数functionTop(){
console.log('防抖'+newDate());}// 滚动事件
window.addEventListener('scroll',debounce(Top,1000));
节流代码:
functionthrottle(fn,t){let delay =500|| t;let time,last;// 通过闭包保存一个标记return(...args)=>{let now =+newDate()// 将多次执行变为每隔一段时间执行if(last && now < last + delay){clearTimeout(time)
time =setTimeout(()=>{
last = now
fn.apply(this,args)},delay)}else{
last = now
fn.apply(this,args)}};}functionsayHi(e){
console.log('节流:', e.target.innerWidth, e.target.innerHeight);}
window.addEventListener('resize',throttle(sayHi,500));