目录
- 性能优化分类
- 实现效果
- 性能优化实现步骤
-
-
- [1. 准备阶段](#1. 准备阶段)
- [2. 防抖函数](#2. 防抖函数)
- [3. 节流函数](#3. 节流函数)
- [4. 调用函数](#4. 调用函数)
-
- 完整实例代码
性能优化分类
防抖和节流
实现效果
防抖
节流
性能优化实现步骤
1. 准备阶段
理解防抖 ,节流的概念以及基本的实现方法
- 防抖:在事件执行过程中,如果被打断,则重新开始计时,只执行最后一次。一般用于鼠标移动事件,页面滚动事件等高频率触发事件
- 节流:在事件执行过程中,如果重复执行,则不中断,直到本次事件执行完毕后,在执行下一次事件,同样用于高频率触发事件
2. 防抖函数
判断是否有定时器,如果有则清除定时器,如果没有则启动计时器
- 函数传入两个参数,第一个为执行函数,第二个为执行时间
- 函数体要写到return中回调,使之重复执行
javascript
function debounce(fun, t) {
let timer
return function () {
if (timer) clearTimeout(timer) //如果存在定时器,则清除定时器
timer = setTimeout(() => {
fun()
}, t)
}
}
3. 节流函数
判断是否有定时器,只有当不存在定时器的时候,启动计时器
- 定时器的返回值为数字
- 一般情况下,定时器内部无法清除定时器,所以要使用timer=null的方式来清除定时器
javascript
function throttle(fun, t) {
let timer = null
return function () {
if (!timer) {
timer = setTimeout(() => {
fun()
timer = null //使用timer=null清除定时器
}, 1000)
}
}
}
4. 调用函数
javascript
function fn1() { //定义执行函数
console.log(111111111)
}
document.querySelector('.box').addEventListener('mousemove', throttle(fn1, 1000)) //调用性能优化函数
完整实例代码
javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
height: 400px;
width: 400px;
background-color: black;
margin: 200px 100px;
}
</style>
</head>
<body>
<div class="box">
</div>
</body>
</html>
<script>
function fn1() {
console.log(111111111)
}
document.querySelector('.box').addEventListener('mousemove', throttle(fn1, 1000))
// 防抖
function debounce(fun, t) {
let timer
return function () {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
fun()
}, t)
}
}
// 节流
function throttle(fun, t) {
let timer = null
return function () {
if (!timer) {
timer = setTimeout(() => {
fun()
timer = null
}, 1000)
}
}
}
</script>