实现方式:
1.lodash提供的节流函数来处理
2.手写一个节流函数来处理
需求:鼠标在盒子上移动,不管移动多少次,每隔500ms才+1
方法一:lodash提供的节流函数来处理
<!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>
<script src="./js/lodash.min.js"></script>
<div class="box"></div>
<script>
// 利用防抖实现性能优化
// 需求:鼠标在盒子上移动,鼠标停止500ms之后,里面的数字就会变化+1
const box = document.querySelector('.box')
let i = 1
function mouseMove() {
box.innerHTML = i++
}
// mousemove鼠标移动事件
// 鼠标一移动就500ms后就触发debounce事件,i就++
// 语法: _.throttle(fun,时间)
box.addEventListener('mousemove', _.throttle(mouseMove, 500))
</script>
</body>
</html>
方法二:手写一个节流函数来处理
实现方式:
节流的核心就是利用定时器setTimeout来实现
1声明一个定时器变量
2每次事件触发时都先判断是否有定时器了,如果有则不开启定时器
3如果没有定时器则开启定时器,存到变量里面
定时器里面调用执行的函数
定时器里面要把定时器清空
<!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>
// 利用防抖实现性能优化
// 需求:鼠标在盒子上移动,鼠标停止500ms之后,里面的数字就会变化+1
const box = document.querySelector('.box')
let i = 1
function mouseMove() {
box.innerHTML = i++
}
// 手写一个节流函数
// 节流的核心就是利用定时器setTimeout来实现
// 1声明一个定时器变量
// 2每次事件触发时都先判断是否有定时器了,如果有则不开启定时器
// 3如果没有定时器则开启定时器,存到变量里面
// 定时器里面调用执行的函数
// 定时器里面要把定时器清空
function throttle(fn, t) {
let timer = null
return function(){
if(!timer){
timer = setTimeout(function(){
fn()
// 时间到了才去清空,时间没到就不能清空,所以要写在里面
timer = null
},t)
}
}
}
box.addEventListener('mousemove', throttle(mouseMove, 500))
// 有括号的函数会直接执行的不用鼠标滑动,所以当鼠标滑动时需要有一个return
// 在setTimeout中是无法删除定时器的,因为定时器还在运作,所以使用timer=null而不是clearTimeout(timer)
</script>
</body>
</html>