前言:
以下代码示例中,都进行调用了 JS 库,可以到以下网站中进行对应下载:Lodash 简介 | Lodash中文文档 | Lodash中文网
https://www.lodashjs.com/
1、关于防抖
概念:在单位时间内,频繁的触发事件,只会执行最后一次
举个栗子:
王者荣耀中的回城,若中途一直打断,则回城失败,需要完整的执行,才能回城成功
示例代码:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>防抖技术的基本使用</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>
<!--进行引入外部 js 库,来进行调用防抖函数-->
<script src="./js/lodash.min.js"></script>
<script>
let num = 0
let myBox = document.querySelector('.box')
function mouseMove() {
num++
myBox.innerHTML = num.toString()
}
// 这里调用防抖函数 【当事件一直不断的被重复触发时,不会生效,只执行最后完整的一次触发流程】
myBox.addEventListener('mousemove', _.debounce(mouseMove, 300))
</script>
</body>
</html>
2、关于节流
概念:需要保证第一次的调用被执行完,才能进行后续的重新触发
举个栗子:
穿越火线中的普通AK,在射击完一个弹夹后,换子弹的期间不能继续射击,需子弹换完之后才能继续进行射击
示例代码:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>节流函数的基本使用</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>
<!--进行引入外部 js 库,来进行调用节流函数-->
<script src="./js/lodash.min.js"></script>
<script>
let num = 0
let myBox = document.querySelector('.box')
function mouseMove() {
num++
myBox.innerHTML = num.toString()
}
// 这里调用节流函数 【就算一直重复触发事件,也需要将第一次触发的流程执行结束,才会执行后续的触发事件】
myBox.addEventListener('mousemove', _.throttle(mouseMove, 1000))
</script>
</body>
</html>