函数防抖和节流

118 阅读1分钟

一 防抖

//函数防抖:当持续触发事件的时候,一定时间段内没有再触发事件,事件处理函数才会执行一次。
//应用场景:input输入框搜索联想,用户在不断输入值时,用防抖来节约请求资源。
//即当用户不在输入,的一秒后,再请求搜索联想资源。

function debounce(fn,delay){
    let timer=null;
    return function(){
        let context=this;
        let arg=arguments;
        if(timer){
            clearTimeout(timer)
        }
        timer=setTimeout(()=>{
            fn.apply(context,arg);
            timer=null;
        },delay)
    }
}

const debounced=debounce(()=>console.log('debounce'),2000);

image.png

二 节流

//函数节流: 当持续触发事件的时候,保证一定时间段内只调用一次事件处理函数
//应用场景:resize,scroll

//时间戳写法,第一次立即执行
function throttle(fn,delay){
    let last=0;
    return function(){
        let now=new Date();
        if(now-last>=delay){
            last=now;
            fn.apply(this,arguments);
        }
    }
}
//定时器写法,第一次不立即执行
function throttle(fn,delay){
    let timer=null;
    return function(){
        let context=this;
        let arg=arguments;
        if(!timer){
            let timer=setTimeout(()=>{
               fn.apply(context,arg);
               timer=null;
            },delay)
        }
    }
}

const throttled=throttle(()=>console.log('throttle'),2000);

image.png