防抖(debounce)是为了减少性能消耗的手段,用于限制连续触发的事件处理函数的执行频率,以减少性能问题或不必要的资源消耗。当事件被触发时,防抖函数会等待一段时间(称为延迟时间),如果在这段时间内没有再次触发该事件,那么才会执行事件处理函数。如果在延迟时间内事件再次被触发,延迟时间会被重新计时。
防抖的基本实现
function debounce(fn, delay, immediate = false) {
let timer = null
// 定义一个变量,来保存第一次需要立即执行
// 不要直接修改传递来的参数
let isOver = false
return function (...args) {
if (!isOver && immediate) {
fn.apply(this, args)
isOver = true
}
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this, args)
isOver = false
}, delay)
}
}
测试用例
<!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 src="./debounce.js"></script>
<script>
const inputEl = document.querySelector('input')
let count = 0
const changeInput = function (event) {
console.log(`触发了${++count}次方法`, this, event);
}
const _debounce = debounce(changeInput, 2000, true)
inputEl.oninput = _debounce
</script>
</body>
</html>