浅谈JavaScript节流和防抖函数
概念
节流函数
间隔固定的时间执行传入的方法
目的是防止函数执行的频率过快,影响性能.常见于跟滚动,鼠标移动事件绑定的功能.
防抖函数
对于接触过硬件的人也许更好理解,硬件按钮按下时,由于用户按住时间的长短不一,会多次触发电流的波动,加一个防抖函数就会只触发一次,防止了无意义的电流波动引起的问题.
按键防反跳(Debounce)为什么要去抖动呢?机械按键在按下时,并非按下就接触的很好,尤其是有簧片的机械开关,会在接触的瞬间反复的开合多次,直到开关状态完全改变。
应用在前端时,常见的场景是,输入框打字动作结束一段时间后再去触发查询/搜索/校验,而不是每打一个字都要去触发,造成无意义的ajax查询等,或者与调整窗口大小绑定的函数,其实只需要在最后窗口大小固定之后再去执行动作.
自己的实现
防抖函数
关键点在于每次触发时都清空延时函数的手柄,只有最后一次触发不会清空手柄,所以最后一次触发会等默认的1s后去执行debounce传入的参数函数f.debounce内部返回的闭包函数,是真正每次被调用触发的函数,不再是原本的f,所以这里的arguments取闭包函数环境变量中的arguments并在执行f时传给f,在setTimeout函数的外面取得.
letdebounce=function(f,interval=1000){
lethandler=null;
returnfunction(){
if(handler){
clearTimeout(handler);
}
letarg=arguments;
handler=setTimeout(function(){
f.apply(this,arg);
clearTimeout(handler);
},interval)
}
}
应用:
letinput=document.querySelector('#input');
input.addEventListener('input',debounce(function(e){
console.log("您的输入是",e.target.value)
}))
更高级的实现还会考虑到,以leading和trailing作为参数,起始先执行一次函数并消除后面的抖动,还是最后执行一下函数,消除前面的抖动,如同我这里的例子.后面分析loadash的防抖函数时会详细解析.
节流函数
letthrottle=function(f,gap=300){
letlastCall=0;
returnfunction(){
letnow=Date.now();
letellapsed=now-lastCall;
if(ellapsed
闭包函数在不断被调用的期间,去记录离上一次调用间隔的时间,如果间隔时间小于节流设置的时间则直接返回,不去执行真正被包裹的函数f.只有间隔时间大于了节流函数设置的时间gap,才调用f,并更新调用时间.
应用:
document.addEventListener('scroll',throttle(function(e){
//判断是否滚动到底部的逻辑
console.log(e,document.documentElement.scrollTop);
}));
lodash源码分析
以上是对节流防抖函数最基础简单的实现,我们接下来分析一下lodash库中节流防抖函数的分析.
节流函数的使用
$(window).on('scroll',_.debounce(doSomething,200));
functiondebounce(func,wait,options){
varlastArgs,
lastThis,
result,
timerId,
lastCallTime=0,
lastInvokeTime=0,
leading=false,
maxWait=false,
trailing=true;
if(typeoffunc!='function'){
thrownewTypeError(FUNC_ERROR_TEXT);
}
wait=wait||0;
if(isObject(options)){
leading=!!options.leading;
maxWait='maxWait'inoptions&&Math.max((options.maxWait)||0,wait);
trailing='trailing'inoptions?!!options.trailing:trailing;
}
functioninvokeFunc(time){
varargs=lastArgs,
thisArg=lastThis;
lastArgs=lastThis=undefined;
lastInvokeTime=time;
result=func.apply(thisArg,args);
returnresult;
}
functionleadingEdge(time){
console.log("leadingEdgesetTimeout")
//Resetany`maxWait`timer.
lastInvokeTime=time;
//Startthetimerforthetrailingedge.
timerId=setTimeout(timerExpired,wait);
//Invoketheleadingedge.
returnleading?invokeFunc(time):result;
}
functionremainingWait(time){
vartimeSinceLastCall=time-lastCallTime,
timeSinceLastInvoke=time-lastInvokeTime,
result=wait-timeSinceLastCall;
console.log("remainingWait",result)
returnmaxWait===false?result:Math.min(result,maxWait-timeSinceLastInvoke);
}
functionshouldInvoke(time){
console.log("shouldInvoke")
vartimeSinceLastCall=time-lastCallTime,
timeSinceLastInvoke=time-lastInvokeTime;
console.log("time",time,"lastCallTime",lastCallTime,"timeSinceLastCall",timeSinceLastCall)
console.log("time",time,"lastInvokeTime",lastInvokeTime,"timeSinceLastInvoke",timeSinceLastInvoke)
console.log("should?",(!lastCallTime||(timeSinceLastCall>=wait)||
(timeSinceLastCall<0)||(maxWait!==false&&timeSinceLastInvoke>=maxWait)))
//Eitherthisisthefirstcall,activityhasstoppedandwe'reatthe
//trailingedge,thesystemtimehasgonebackwardsandwe'retreating
//itasthetrailingedge,orwe'vehitthe`maxWait`limit.
return(!lastCallTime||(timeSinceLastCall>=wait)||
(timeSinceLastCall<0)||(maxWait!==false&&timeSinceLastInvoke>=maxWait));
}
functiontimerExpired(){
console.log("timerExpired")
vartime=Date.now();
if(shouldInvoke(time)){
returntrailingEdge(time);
}
console.log("Restartthetimer.",time,remainingWait(time))
//Restartthetimer.
console.log("timerExpiredsetTimeout")
timerId=setTimeout(timerExpired,remainingWait(time));
}
functiontrailingEdge(time){
clearTimeout(timerId);
timerId=undefined;
//Onlyinvokeifwehave`lastArgs`whichmeans`func`hasbeen
//debouncedatleastonce.
console.log("trailing",trailing,"lastArgs",lastArgs)
if(trailing&&lastArgs){
returninvokeFunc(time);
}
lastArgs=lastThis=undefined;
returnresult;
}
functioncancel(){
if(timerId!==undefined){
clearTimeout(timerId);
}
lastCallTime=lastInvokeTime=0;
lastArgs=lastThis=timerId=undefined;
}
functionflush(){
returntimerId===undefined?result:trailingEdge(Date.now());
}
functiondebounced(){
vartime=Date.now(),
isInvoking=shouldInvoke(time);
console.log("time",time);
console.log("isInvoking",isInvoking);
lastArgs=arguments;
lastThis=this;
lastCallTime=time;
if(isInvoking){
if(timerId===undefined){
returnleadingEdge(lastCallTime);
}
//Handleinvocationsinatightloop.
clearTimeout(timerId);
console.log("setTimeout")
timerId=setTimeout(timerExpired,wait);
returninvokeFunc(lastCallTime);
}
returnresult;
}
debounced.cancel=cancel;
debounced.flush=flush;
returndebounced;
}
ref
https://css-tricks.com/debouncing-throttling-explained-examples/
https://github.com/lodash/lodash/blob/4.7.0/lodash.js#L9840
https://jinlong.github.io/2016/04/24/Debouncing-and-Throttling-Explained-Through-Examples/
以上就是浅谈JavaScript节流和防抖函数的详细内容,更多关于JavaScript节流和防抖函数的资料请关注毛票票其它相关文章!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。