概念功能防抖和功能节流,都是一种优化js代码高频执行的手段。防抖概念:所谓防抖是指事件触发后,该功能在n秒内只能执行一次。如果在n秒内再次触发该事件,函数执行时间将重新计算。点我去抖动!$('#debounce').on('click',debounce());functiondebounce(){让定时器;返回函数(){clearTimeout(计时器);timer=setTimeout(()=>{//需要防抖的操作...console.log("防抖成功!");},500);}}功能防抖最常见的应用场景就是页面滚动条监控的例子,来分析一下:lettimer;window.onscroll=function(){clearTimeout(timer);timer=setTimeout(function(){//滚动条位置letscrollTop=document.body.scrollTop||document.documentElement.scrollTop;console.log('滚动条位置:'+scrollTop);},200)}的封装防抖功能/***防抖功能*@paramfn事件触发操作*@paramdelay多少毫秒连续触发事件,不会执行*@returns{Function}*/functiondebounce(fn,delay){让定时器=null;returnfunction(){letself=this,args=arguments;计时器&&清除超时(计时器);timer=setTimeout(function(){fn.apply(self,args);},delay);}}window.onscroll=debounce(function(){letscrollTop=document.body.scrollTop||document.documentElement.scrollTop;console.log('scrollbarposition:'+scrollTop);},200)节流概念:只在指定的时间间隔内执行一个任务(js方法在一定时间内只运行一次)点我节流!$('#throttle').on('click',throttle());functionthrottle(fn){letflag=true;返回函数(){if(!flag){返回;}标志=假;setTimeout(()=>{console.log("节流成功!");flag=true;},1000);};}图片说明:功能节流应用实际场景,根据文本框中输入的内容自动请求后台数据。下面是节流函数的封装和使用:$('#input').on('keyup',throttle(function(){.log($(this).val());//ajax后台请求....},1000));/***节流函数*@paramfn事件触发操作*@paramdelay多少毫秒到触发一个事件*/functionthrottle(fn,delay){letflag=true;returnfunction(){letself=this,args=arguments;如果(!标志){返回;}标志=假;setTimeout(()=>{fn.apply(self,args);flag=true;},delay);}}