防抖函数解决的问题:
防止误操作等多次输出点击等事件造成的多次通信请求。
### 防抖代码如下: ``` const debounce = (fn, delay = 1000) => { let timer = null; return (...args) => { console.log(`clear timer:`, this.timer); //必须要写this. console.log(`_that===this :`, _that === this); clearTimeout(this.timer); this.timer = setTimeout(() => { fn.apply(this, args); }, delay); console.log(`timer value:`, this.timer); }; };### html占用调用
防抖点击
function clickFun(){
alert(’'点击");
}
</br>
## 节流函数解决的问题:
### 当dom布局频繁Resize时需要使用节流函数减少回流或重绘的次数。
### 节流函数代码如下:
const throttle=(fn,delay=1000)=>{
let flag=false;
return (…args)=>{
if(this.flag)return;
this.flag=true;
setTimeout(() => {
fn.apply(this,args);
this.flag=false;
}, delay);
}
}
### html中调用:
节流点击
function clickFun(){
alert(’'点击");
}
### TODO:下次将写一篇关于前端性能优化的文章(三方面:通讯优化、首屏渲染优化、界面操作性能优化)