当前位置: 首页 > Web前端 > HTML

防抖节流功能

时间:2023-04-02 16:45:38 HTML

防抖功能解决的问题:防止多次输出点击导致的多次通信请求等误操作等事件。debounce代码如下:constdebounce=(fn,delay=1000)=>{lettimer=null;return(...args)=>{console.log(`cleartimer:`,this.timer);//必须这样写。console.log(`_that===this:`,_that===this);clearTimeout(this.timer);this.timer=setTimeout(()=>{fn.apply(this,args);},延迟);console.log(`timervalue:`,this.timer);};};html占用调用debounceclick函数clickFun(){alert(''click");}节流函数解决问题:当dom布局频繁调整大小,需要使用节流功能减少回流或重绘的次数。throttle函数代码如下:constthrottle=(fn,delay=1000)=>{letflag=false;return(...args)=>{if(this.flag)return;这个。标志=真;setTimeout(()=>{fn.apply(this,args);this.flag=false;},delay);}}在html中调用:throttleclickfunctionclickFun(){alert(''click");}TODO:我会写一篇关于前端的文章下次性能优化(三个方面:通信优化、首屏渲染优化、界面操作性能优化)