防抖与节流的区别:
防抖: 将多次执行变为最后一次执行
节流: 将多次执行变为每隔一段时间执行
<!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>防抖与节流</title>
<style>
.box {
background-color: green;
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<input type="text" placeholder="请输入电话号码" />
<div class="box"></div>
<script>
let telInput = document.querySelector("input");
telInput.addEventListener("input", antiShake(demo, 2000));
// 封装防抖
function antiShake(fn, wait) {
let timeOut = null;
return (args) => {
if (timeOut) {
clearTimeout(timeOut);
}
timeOut = setTimeout(fn, wait);
};
}
function demo() {
console.log("发送请求");
}
let box = document.querySelector("div");
box.addEventListener("touchmove", throttle(demo, 2000));
// 封装节流
// 应用场景:提交表单、高频监听事件
function throttle(fn, time) {
let timer = null;
return () => {
if (!timer) {
timer = setTimeout(() => {
fn();
timer = null;
}, time);
}
};
}
</script>
</body>
</html>