短时间内多次触发同一事件,在一定的时间内只执行最后一次

防抖使用的场景:通常可以用来做按钮的防二次点击、搜索的时候执行最后一次请求、通过resize不断改变浏览器大小的时候,只执行最后一次

function debounce(handler,delay){
    let timer=null;
    return function(){
        if(timer){
            clearTimeout(timer);
        }
    timer=setTimeout(hander,delay)
    }
}
function hander(){}
debounce(hander,1000);

节流

多次触发同一事件,第一次执行以后事件就会失效,直到过了指定的时间事件才会再次生效。

节流适用的场景:多用于监听滚动事件,比如滑到页面底部加载更多

function throttle(handle,delay){
    let time=Date.now();
    return function(){
        let now=Data.now();
        if(now-time>=delay){
            setTimeout(()=>{
                handle();
                time=Date.now();
            },delay)
        }
    }
}
function handle(){}
throttle(handle,1000)