节流概念:
单位时间内,频繁触发事件,只执行一次
使用场景:
高频事件mousemove,页面尺寸缩放resize,滚动条滚动sroll等等
手写节流函数:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>手写节流</title>
<style>
.box1 {
height: 200px;
width: 200px;
background-color: #ccc;
color: #fff;
font-size: 30px;
line-height: 200px;
text-align: center;
margin: 100px auto;
}
</style>
</head>
<body>
<div class="box1">0</div>
<script>
// 获取元素
const box1 = document.querySelector('.box1')
let i = 0;
function mouseMove() {
box1.innerHTML = i++
}
// 添加鼠标移动事件
// 手写节流
function throttle(fn, t) {
// 声明一个变量存储计时器变量
let timerId
return function() {
// 判断是否有计时器
if(!timerId) {
// 当没有计时器时
timerId = setTimeout(() => {
fn()
timerId = null
}, t)
}
}
}
box1.addEventListener('mousemove', throttle(mouseMove, 2000))
</script>
</body>
</html>