共同点
共同点:在高频触发事件中限制触发频次,减少不必要的内存耗费
区别
防抖(debounce)处理:n秒内多次触发只执行最后一次触发(若一直触发,只执行最后一次触发)
节流(throttle)处理:n秒内多次触发只执行第一次触发(若一直触发,每隔n秒触发一次)
示例
- input事件节流处理
- window.resize事件防抖
<!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>
<style>
.box1 {
border: 1px solid red;
padding: 20px;
}
.box2 {
border: 1px solid blue;
padding: 20px;
margin-top: 20px;
}
</style>
</head>
<body>
<div class="box1">
<h1>节流场景(input事件)</h1>
<input id="input" type="text" oninput="handleInput()" />
<p id="inputValue"></p>
</div>
<div class="box2">
<h1>防抖场景(监听窗口变化)</h1>
<p id="screenHeightValue"></p>
</div>
</body>
<script>
//节流
function throttle(fn, delay) {
let run = true;
return function () {
if (!run) return;
run = false;
setTimeout(() => {
fn.apply(this, arguments);
run = true;
}, delay);
};
}
const handleInput = throttle(() => {
const value = document.getElementById("input").value;
document.getElementById("inputValue").innerText = value;
console.log("输入了", value);
}, 1000);
//防抖
function debounce(fn, delay) {
let timer = null;
return function () {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(fn, delay);
};
}
window.addEventListener(
"resize",
debounce(() => {
const screenHeight = document.documentElement.clientHeight;
document.getElementById("screenHeightValue").innerText = screenHeight;
console.log("窗口变化了", screenHeight);
}, 500)
);
</script>
</html>