前端经常会遇到事件不断调用的问题,所以油门功能和防抖功能必不可少。我个人一般是在封装好的公共组件里面包裹一层,防止事件的重复调用。油门函数直接编码functionthrottle(fn,delay){letrunning=true;returnfunction(){if(running){fn.apply(this,arguments);console.log("参数",参数[0]);运行=假;setTimeout(()=>{running=true;},delay);}};}functionneedThrottle(){console.log("hihihi");}consttest=throttle(needThrottle,200);test(1);test(2);test(3);从打印出来的arguments[0]可以看出,执行了第一次调用的函数。防抖功能functiondebounce(fn,delay){lettimer=null;返回函数(){if(timer){clearTimeout(timer);}timer=setTimeout(()=>{fn.apply(this,arguments);console.log('arguments',arguments[0]);timer=null;},delay);};}constdebounced=debounce(()=>console.log("hi"));debounced(1);去抖动(2);去抖动(3);从打印出来的arguments[0]可以看出最后调用的函数被执行了。
