节流:单位时间内,频繁触发事件,只执行一次
节流实现方式:
在wait秒内最多执行func一次
也就是说“在wait秒内不管触发多少次,都只调一次func”
目标:鼠标在盒子上移动,不管移动多少次,每隔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++
}
box.addEventListener('mousemove',_.throttle(mouseMove,3000))
</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++
}
function throttle(fn,t){
let timer = null
return function(){
if(!timer){
timer = setTimeout(function(){
fn()
//清空定时器
timer=null
},t)
}
}
}
//return个匿名函数,这样才能多次执行;否则是调用的话,它只会执行一次
box.addEventListener('mousemove',throttle(mouseMove,3000))
</script>
</body>
</html>
清空定时器为什么采用timer=null;而非clearTimeout(timer)
因为在setTimeout中是无法清除定时器的,因为定时器还在运作;不合理
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- bangwoyixia.com 版权所有 湘ICP备2023022004号-2
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务