防抖:单位时间内,频繁触发事件,只执行最后一次
防抖实现方式:
目标:鼠标在盒子上移动,鼠标停止500ms之后,里面的数字才会变化+1
<!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: 500px;
height: 500px;
background-color: #ccc;
color: #fff;
text-align: center;
font-size: 100px;
}
</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++
}
//语法:_.debounce(fun,时间)
box.addEventListener('mousemove', _.debounce(mouseMove, 500))
</script>
</body>
</html>
思路:
<!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: 500px;
height: 500px;
background-color: #ccc;
color: #fff;
text-align: center;
font-size: 100px;
}
</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))
function debounce(fn,t){
//1.
let timer
//return 返回一个匿名函数
return function(){
//2.3.4
if(timer) clearTimeout(timer)
timer = setTimeout(function(){
//在定时器里执行要执行的函数mouseMove()
fn()
}, t)
}
}
// 为什么返回一个匿名函数?
// debounce(mouseMove, 500)单写这个是函数调用;只执行一次
// debounce(mouseMove, 500) 接收 function(){2,3,4}
// 就相当于box.addEventListener('mousemove',function(){2,3,4})
box.addEventListener('mousemove',debounce(mouseMove, 500))
</script>
</body>
</html>
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- bangwoyixia.com 版权所有 湘ICP备2023022004号-2
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务