性能优化
防抖
防抖(debounce)
所谓防抖,就是指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间
<style> .box { width: 500px; height: 500px; background-color: #ccc; color: #fff; text-align: center; font-size: 100px; } </style>
<div class="box"></div> <script src="./lodash.min.js"></script>
const box = document.querySelector('.box') let count = 0 function mouseMove () { box.innerHTML = ++count } function debounce (fn, t = 500) { let timer return function () { if(timer) clearTimeout(timer) timer = setTimeout(fn, t) } } //自定义 // box.addEventListener('mousemove', debounce(mouseMove, 500)) //Lodash库 box.addEventListener('mousemove', _.debounce(mouseMove, 500))
节流
节流(throttle)
所谓节流,就是指连续触发事件但是在 n 秒中只执行一次函数
使用场景 :轮播图点击效果 、 鼠标移动、页面尺寸缩放resize、滚动条滚动 就可以加节流
<script> const box = document.querySelector('.box') let i = 0 function mouseMove () { box.innerHTML = ++i } // 节流函数 // 控制box上文本多长时间修改一次 function throttle (fn, t = 500) { // 开始时间 let startTime = 0 return function () { // 当前时间 let now = Date.now() console.log(now) // 每隔500ms执行一次函数fn if(now - startTime >= t){ // 调用函数 fn() // startTime设置成当前时间 startTime = now } } } // 监听事件 //自定义 //box.addEventListener('mousemove', throttle(mouseMove, 500)) //lodash库 box.addEventListener('mousemove', _.throttle(mouseMove, 500)) </script>
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性