用闭包方式实现防抖节流

128 阅读1分钟
   <div onclick="de()" class="button">防抖</div>
   <div onclick="th()" class="button">节流</div>
function fun(){console.log(1)}//功能函数
//防抖
function debounce(fun,delay){
        let timer=null;
        return function(){
                if(timer!==null) {clearTimeout(timer)}
                timer=setTimeout(fun,delay)
        }
}
//节流
function throttle(fun,delay){
        let throttleTimer,throttleFlag;
        return function(){
                if(!throttleFlag){
                        throttleFlag=true;
                        throttleTimer=setTimeout(function(){
                                throttleFlag=false
                                fun()
                        },delay)
                }
        }
}
let de=debounce(fun,2000)
let th=throttle(fun,2000)