1. 防抖概述
- 多次触发事件,事件处理函数只能执行一次,并且是在触发操作结束时执行。
2. 应用场景——搜索框搜索
2.1 未防抖之前
<!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>
</head>
<body>
<input type="text" />
<script>
let ipt = document.querySelector("input");
ipt.oninput = function () {
console.log(this.value);
};
</script>
</body>
</html>
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/7be48dec11f64ff9ebeb5502cc6222a3.png)
2.2 防抖之后
<!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>
</head>
<body>
<input type="text" />
<script>
let ipt = document.querySelector("input");
ipt.oninput = debounce(function () {
console.log(this.value);
}, 500);
function debounce(fn, delay) {
let timer = null;
return function () {
clearTimeout(timer);
timer = setTimeout(() => {
fn.call(this);
}, delay);
};
}
</script>
</body>
</html>
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/9d210096f05987c20c0af6dc67db8180.png)