什么是防抖?
概念:函数防抖(debounce),就是指触发事件后,在 n 秒内函数只能执行一次,如果触发事件后在 n 秒内又触发了事件,则会重新计算函数延执行时间。
例子:王者荣耀点击回城后,只有时间一到才会回到泉水。如果回城时被打断就只能重新计时回城的时间。
需求:
鼠标在盒子上移动,里面的数字就会变化。
法1.lodash库里的_.debounce(fun,时间)
参考链接:lodash库里的_.debounce(fun,时间)
<!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>Document</title>
<style>
.box {
width: 200px;
height: 200px;
background-color: pink;
}
</style>
</head>
<body>
<div class="box"></div>
<script src="./lodash.min.js"></script>
<script>
const box = document.querySelector('.box')
let i = 1
function mouseMove() {
box.innerHTML = i++
}
box.addEventListener('mousemove', _.debounce(mouseMove, 500))
</script>
</body>
</html>
法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>Document</title>
<style>
.box {
width: 200px;
height: 200px;
background-color: pink;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
const box = document.querySelector('.box')
let i = 1
function mouseMove() {
box.innerHTML = i++
}
// 核心是利用setTimeout定时器来实现
// 1.声明定时器变量
// 2.每次鼠标移动(事件触发)的时候要先判断是否有定时器,如果有先清除以前的定时器
// 3.如果没有定时器,则开启定时器,存入到定时器变量里面
// 4.定时器里面写函数调用
function debounce(fn, t) {
console.log(111);
let timer
// return一个匿名函数
return function () {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(function () {
fn()
}, t)
}
}
box.addEventListener('mouseover', debounce(mouseMove, 500))
</script>
</body>
</html>
效果:
参考:黑马前端教程