定义:
防抖:在规定时间内多次触发事件,只有效的执行最后一次事件。
节流:当多次触发事件时,稀释点击频率,只在规定的时间间隔内触发一次事件。
作用:
防抖&节流:避免因高频事件导致程序执行无效的加载、提交等,避免性能损耗和程序崩溃等问题。
防抖函数:
let timer = null;
function antiShake() {
clearTimeout(timer);
timer = setTimeout(() => {
console.log('防抖');
}, 1000);
}
节流函数:
let timer = null;
let lastTime = null;
function throttle() {
let now = new Date().getTime();
if (now - lastTime > 1000) {
console.log('节流');
lastTime = now;
}
}
function throttle1() {
if (!timer) {
timer = setTimeout(() => {
console.log('节流');
}, 1000);
} else {
timer = null;
clearTimeout(timer);
}
}
案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div class="container">
<div class="container_left" onclick="antiShake()">aaa</div>
<div class="container_right" onclick="throttle()">bbb</div>
</div>
</body>
</html>
<script>
let timer = null;
let lastTime = null;
function antiShake() {
clearTimeout(timer);
timer = setTimeout(() => {
console.log('防抖');
}, 1000);
}
function throttle() {
let now = new Date().getTime();
if (now - lastTime > 1000) {
console.log('节流');
lastTime = now;
}
}
function throttle1() {
if (!timer) {
timer = setTimeout(() => {
console.log('节流');
}, 1000);
} else {
timer = null;
clearTimeout(timer);
}
}
</script>
<style>
body {
padding: 0;
margin: 0;
}
.container {
width: 100vw;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
font-size: 36px;
font-weight: bold;
color: #fff;
}
.container_left {
width: 200px;
height: 200px;
margin-right: 100px;
border-radius: 10px;
background: red;
line-height: 200px;
text-align: center;
}
.container_right {
width: 200px;
height: 200px;
border-radius: 10px;
background: blue;
line-height: 200px;
text-align: center;
}
</style>
如果实用的话记得给颗赞嚯!