性能优化

防抖

防抖(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>
posted @   丫丫learning  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
点击右上角即可分享
微信分享提示