目录
防抖概念:
单位时间内,频繁触发事件,只执行最后一次
使用场景:
1. 搜索框输入,用户最后一次输入完再发送请求
2. 手机号,邮箱验证输入监测
手写防抖函数:
<!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 debounce(fn, t) {
// 定义一个变量存放计时器编号
let timerId
return function() {
// 判断之前有没有定时器
if(timerId) {
// 定时器,清除定时器
clearTimeout(timerId)
}
// 这里不能放在 else 中 是因为清除一个定时器后还要开启下一个定时器
timerId = setTimeout(fn, t)
}
}
box1.addEventListener('mousemove', debounce(mouseMove, 500))
</script>
</body>
</html>