js节流和防抖

函数节流(Throttle)

定义:指定的时间间隔内只执行一次任务app

function Throttle(fn,delay){
    let last,timer;
    return function(){
        let that = this;
        let _args = arguments;
        let now = +new Date();//等价 new Date().getTime()
        if(last && now < last + delay){
            clearTimeout(timer);
            timer = setTimeout(function(){
                last = now;
                fn.apply(that,_args);
            },delay)
        }else {
            last = now;
            fn.apply(that,_args);
        }
        
    }
    
}
复制代码

防抖(debounce)

定义:在事件被触发n秒后再执行回调,若是在这n秒内又被触发,则从新计时函数

function debounce(fn,delay){
    let timer = null;
    return function(){
        let that = this;
        let _args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function(){
            fn.applay(that,_args);
        },delay)
    }
}
复制代码

应用场景:

debounce(防抖):

1.输入框进行搜索,用户在不断进行输入的时候,不去请求,用防抖来节约请求资源; 2.window触发resize的时候,会不断触发回调,用防抖来让其只触发一次this

throttle(节流):

1.鼠标不断点击触发,或按钮不断被点击触发 2.监听滚动事件,好比滚动到底部自动加载,用throttle判断spa

相关文章
相关标签/搜索