防抖和节流 (面试手写题)
防抖: 在指定的时间内代码只执行一次(频繁触发事件时, 代码不会执行的,当在指定的时间内不在触发事件时, 代码会执行一次, 当不再触发事件时,代码也不再执行)
节流: 每间隔指定的时间内代码都会执行一次(频繁触发事件时,只要等待够预定的时间, 代码都会执行一次,当不再触发事件时,代码也不再执行)
频繁触发的事件:
键盘输入事件
鼠标滚轮事件
页面滚动事件
1 <div class="wrap" id="wrap" style="width:100px; height:100px; overflow:auto"> let timer = null; 2 function debounce(){ 3 if(timer){ 4 // 计时器中的函数才是真正的事件处理程序 5 clearTimeout(timer) 6 } 7 timer = setTimeout(move, 1000); 8 }</div> 9 10 <div class="box" style="height:2000px"></div>
1 // js 2 // 防抖 debounce 3 function move() { 4 console.log(this); 5 console.log('事件执行'); 6 } 7 8 /* let timer = null; 9 function debounce(){ 10 if(timer){ 11 // 计时器中的函数才是真正的事件处理程序 12 clearTimeout(timer) 13 } 14 timer = setTimeout(move, 1000); 15 } */ 16 17 // window.addEventListener('scroll', debounce) 18 19 // fn 事件处理程序 deday 等待的时间间隔 20 function debounce(fn, delay) { 21 let timer = null; 22 return function () { 23 if (timer) { 24 clearTimeout(timer) 25 } 26 console.log('计时器外边', this); 27 // 存储this指向 28 let _this = this; 29 // 储存 event (参数) 30 let args = arguments; 31 timer = setTimeout(function () { 32 console.log(1, this); 33 fn.apply(_this, args) 34 }, delay) 35 } 36 } 37 wrap.addEventListener('scroll', debounce(move, 2000)); 38 39 40 41 // =================== 节流 throttle 42 // 计时器 + 时间差 43 // function throttle(fn, delay) { 44 // // 声明计时器 45 // let timer = null; 46 // // 获取当前的时间 事件开始触发时的时间 47 // let start = Date.now(); 48 // return function () { 49 // // 实时获取当前时间 50 // let end = Date.now(); 51 // let _this = this; 52 // let args = arguments; 53 // // 计算时间差 54 // if (end - start > delay) { 55 // clearTimeout(timer) 56 // timer = setTimeout(function () { 57 // fn.apply(_this, args) 58 // }, delay) 59 // start = end; 60 // } 61 // } 62 // } 63 64 // window.addEventListener('scroll', throttle(move, 2000))
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构