函数防抖和函数节流
2018-12-10 17:34
260 查看
首先分别用一句话区分函数防抖和节流的区别。
函数防抖就是在用户停下相应动作,并在给定时间过去之后仅被调用一次。
函数节流是用户在执行相应动作时,每隔一段时间发一次请求。
针对一些频繁触发的事件如scroll、keyup、resize,如果正常绑定事件的话,可能在很短的时间内连续触发事件,十分影响性能。
这里可以用防抖和节流来优化页面。
函数防抖
举个栗子,用户的输入事件keyup怎么处理呢?
timer=null; keyupHandler(){ this.timer && clearTimeout(this.timer); this.timer = setTimeout(this.getData.bind(this),2000) } getData(): void { this.options={ "acctNo":this.acctNo, "keyword":this.keyWord }; this.bdService .getDataByPost(this.getEmpUrl,this.options) .then((res)=>{ if ( res.code === 0) { this.empInfo=res.data; } }) }
每次事件被触发,都会先清除当前的timer然后重新设置超时调用,使得每次触发都会取消前一次的超时调用,只有当用户停止相应动作,最后一次事件会在2秒之后触发。
函数节流
同样是输入事件keyup,每隔2s触发一次。
canRun:boolean=true; keyupHandler(){ if (!this.canRun) { return; } this.canRun = false; setTimeout(function(){ this.options={ "acctNo":this.acctNo, "keyword":this.keyWord }; this.bdService .getDataByPost(this.getEmpUrl,this.options) .then((res)=>{ if ( res.code === 0) { this.empInfo=res.data; } }) this.canRun = true; }.bind(this), 2000); }
函数节流的要点是,声明一个变量当标志位
canRun,记录当前代码是否在执行。
如果canRun = true,表示事件空闲,可以使用。
将canRun=false表示事件正在执行,2s之后再触发请求。