防抖
一、什么是防抖
在一定时间间隔内,多次触发相同事件,只执行最后一次触发事件。
二、场景
2.1 疯狂点击一个按钮,我想时间只触发一次
1 2 3 4 5 6 7 8 9 10 11
| const btn = document.querySelector(".btn")
let timer = null btn.addEventListener("click", () => { if (timer) { clearTimeout(timer) } timer = setTimeout(() => { console.log("点击了按钮") }, 1000) })
|
2.2 当窗口大小发生变化时,会频繁的触发 resize 事件
1 2 3 4 5 6 7 8 9
| let timer = null window.addEventListener("resize", function () { if (timer) { clearTimeout(timer) } timer = setTimeout(function () { console.log("窗口大小改变了") }, 1000) })
|
2.3 搜索输入框,当用户停止输入,才像服务器发送请求
1 2 3 4 5 6 7 8 9 10 11
| let input = document.getElementById("input")
let timer = null input.addEventListener("input", () => { if (timer) { clearTimeout(timer) } timer = setTimeout(() => { console.log("最终输入内容:", input.value) }, 1000) })
|
三、封装防抖函数,直接使用
1 2 3 4 5 6 7 8 9
| function debounce(fn, timeout) { let timer = null return function () { if (timer) clearTimeout(timer) timer = setTimeout(() => { fn() }, timeout) } }
|