防抖 节流

166 阅读1分钟

防抖 debounce

  在连续触发某个函数的时候  我们在最后的时候 让对应的函数执行;
function debounce(fn, wait){
    wait=wait || 1000;
    let timer=null;
    return function(){
        clearTimout(timer);
        timer=setTimout(()=>{
         fn.apply(this,arguments);
        },wait)
    }
}
let f = debounce(function () { console.log(666) });
    window.onscroll = f;

节流 throttle

 在连续触发某个函数的时候       我们每隔一段时间就触发一次该函数
 function throttle(fn,wait){
     wait =wait || 1000;
     let flag=true;
     return function(){
           if(!flag) return;
           flag=false;
         setTimout(()=>{
            fn.apply(this,arguments);
            flag=true;
         ,wait)
     }
 }
 function f() {
        console.log(6666);
    }
    window.onscroll = throttle(f);