通过闭包实现简单版事件节流
const throttle=(fn,timeout)=>{
const context=this
return ()=>{
setTimeout(()=>{
fn.apply(context);
},timeout)
}
}
window.onresize=throttle(()=>{console.log(window.body.clientWidth)},60)
加入时间间隔实现触发执行的时间间隔
const throttle=(fn,timeout,runTimeout)=>{
const context=this;
let _startTime=0;
return ()=>{
const _currentTime=new Date().getTime()
if(!_startTime||_currentTime-_startTime>runTimeout){
fn.apply(context);
_startTime=_currentTime
}else{
setTimeout(()=>{
fn.apply(context);
},timeout)
}
}
}
window.onresize=throttle(()=>{console.log(window.body.clientWidth)},60,100) //100毫秒必须会执行一次,60内重复调用会过滤掉