防抖
在第一次触发事件时,不立即执行函数,而是在一定时间后再执行,如果重新触发事件,则重新执行。
let debounceTimer = null;
debounce(func,delayTime,that,arg){
if(this.debounceTimer){
clearTimeout(this.debounceTimer);
}
this.debounceTimer = setTimeout(()=>{
func.apply(that,arg);
clearTimeout(this.debounceTimer);
},delayTime);
}
节流
在函数执行一次之后,一段时间内再次点击也不会触发操作,需等待时间过后才会再次生效
节流的思路大致与防抖相同,区别在于,节流第一次进来时就调用方法,然后再清除定时器,同样节流也可以自己封装闭包
//定义全局变量
let throttleTimer = null;
throttle(func, delayTime, that, arg){
if(!this.throttleTimer){
func.apply(that,arg);
this.throttleTimer = setTimeout(()=>{
clearTimeout(this.throttleTimer);
},delayTime)
}
}
throttle(func, 2000, this, arguments)