# 手写防抖
# 定义
防抖: n 秒后在执行该事件,若在 n 秒内被重复触发,则重新计时
# 代码实现
设计思路:事件触发后开启一个定时器,如果事件在这个定时器限定的时间内再次触发,则清除定时器,在写一个定时器,定时时间到则触发。
在防抖函数中,我们使用了闭包来保存定时器变量 timer 和传入的函数 func。每次触发事件时,我们先清除之前的定时器,再设置一个新的定时器。如果在 delay 时间内再次触发事件,就会清除之前的定时器并设置一个新的定时器,直到 delay 时间内不再触发事件,定时器到达时间后执行传入的函数 func。
function debounce(fn, delay){
let timer = null;
return function(){
if (timer) clearTimeout(timer)
timer = setTimeout(()=> {
fn.apply(this, arguments);
}, delay)
}
}
# 生产实践
input 搜索

<!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>debounce</title>
</head>
<body>
<p>debounce</p>
搜索 <input id="input1" />
<script>
function debounce(fn, delay = 200) {
let timer = 0
return function () {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this, arguments) // 透传 this 和参数
timer = 0
}, delay)
}
}
const input1 = document.getElementById('input1')
input1.addEventListener(
'keyup',
debounce(() => {
console.log('发起搜索', input1.value)
}),
300
)
</script>
</body>
</html>