防抖(Debounce)是指在一定时间内,当函数被频繁触发时,只有在最后一次触发后的延迟时间内,函数才会被真正执行。如果在延迟时间内又有触发事件发生,会重新开始计时。
简洁的讲就是:n秒后执行该事件,在n秒内被重复触发,则重新计时。
代码实现:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<style>
#btn {
width: 100px;
height: 40px;
margin: 40px;
background-color: aqua;
cursor: pointer;
border: solid 2px #000;
border-radius: 5px;
}
</style>
</head>
<body>
<div>
<button type="button" id="btn">点击我</button>
</div>
<script type="text/javascript">
//获取 按钮
let btn = document.querySelector('#btn');
// “点击我”的方法
function palyClick() {
// console.log(this);
console.log('哈哈哈,我被你点击了');
}
// 封装防抖函数
// func: 点击按钮要执行的函数
// delay: 延迟时间
function debounce(func, delay) {
// 设置定时器标识
let timer = null;
//注意这里不能使用箭头函数 否则会改变this的指向
return function () {
let _this = this;
// 清除 timer 延时方法
if (timer !== null) {
// 清除定时器
clearTimeout(timer);
}
//设置定时器
timer = setTimeout(() => {
func.apply(_this);
timer = null;
}, delay)
}
}
// 给按钮添加d点击事件监听 点击时,执行debounce函数,延时时间为1000
btn.addEventListener('click', debounce(palyClick, 2000));
</script>
</body>
</html>
效果视频:
节流(Throttle)是指在一定时间内,无论函数被触发多少次,函数只会在固定的时间间隔内执行一次。如果在时间间隔内有多次触发事件,只会执行最后一次。
简洁的讲就是:n秒内只运行一次,在n秒内重复被触发,只有最后一次是生效。
代码实现:
<!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>
#btn {
width: 100px;
height: 40px;
margin: 40px;
cursor: pointer;
}
</style>
</head>
<body>
<button id="btn">触发按钮</button>
<script>
//获取 按钮
const btn = document.getElementById("btn");
// “触发按钮”的方法
function playClick() {
console.log("节流方法已经触发");
}
// 封装节流函数
function Throttle(Fun, time) {
let flag = false
return function () {
//首次执行方法,flag置为true
if (!flag) {
Fun();
flag = true;
}
//当定时器中回调函数执行完,将flag置为false时,才会重新执行方法语句
setTimeout(() => {
flag = false;
}, time)
}
};
btn.onclick = Throttle(playClick, 3000);
</script>
</body>
</html>
效果视频:
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。