1、防抖
**定义:**单位时间内,频繁触发事件,只执行最后一次
防抖的解决方案:
引入 lodash 一个方法搞定防抖
_.debounce() 方法
参数1:传入要防抖的函数
参数2:延时的时间
返回值:防抖后的函数
代码里面有使用 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>
<!-- 要先引入外部的js文件 -->
<script src="./lodash.min.js"></script>
<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>
let i = 0
// 绑定鼠标移入事件
function moveFn(){
i++
this.innerHTML = i
}
// _.debounce() 方法
// 参数1:传入要防抖的函数
// 参数2:延时的时间
// 返回值:防抖后的函数
document.querySelector('div').addEventListener('mousemove',_.debounce(moveFn,300))
document.querySelector('div').addEventListener('mousemove', debounce(moveFn, 300))
// 手写的节流函数
// 参数1: 传入的函数,我们需要对他进行防抖处理
// 参数2: 防抖延时的时间
function debounce(fn, time) {
let timeId
return function () {
clearTimeout(timeId)
timeId = setTimeout(() => {
fn.call(this)
}, time)
}
}
</sc
</script>
</body>
</html>
2、节流
**定义:**单位时间内,频繁触发事件,只执行一次
代码里面有用引用外部节流的方法 _.throttle() 方法,还有手写的节流方法
<!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>
<!-- 要先引入外部的js文件 -->
<!-- <script src="./lodash.min.js"></script> -->
<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>
let i = 0
// 绑定鼠标移入事件
function moveFn() {
i++
this.innerHTML = i
}
// _.throttle() 方法
// 参数1:传入要节流的函数
// 参数2:延时的时间
// 返回值:节流后的函数
// document.querySelector('div').addEventListener('mousemove', _.throttle(moveFn, 500))
document.querySelector('div').addEventListener('mousemove', throttle(moveFn, 500))
// 手写的节流函数
function throttle(fn, time) {
let timeId
// 节流有返回值 是函数
return function() {
// 判断是否开启过定时器,如果没有才能开启
if(!timeId){
// 开启定时器
timeId = setTimeout(() => {
// 修改 this 的指向
fn.call(this)
// 清空 timeId 变量
timeId = null
}, time)
}
}
}
</script>
</body>
</html>
防抖和节流的总结:
**手写防抖函数:**只要有定时器就要清除定时器开启
**手写节流函数:**判断内存中有没有正在开启的定时器,如果有就不能再开了,如果没有才开启定时器,定时器执行时记得清除定时器 id 标识