防抖函数是什么?
- 本质上是一种优化策略,浏览器的resize,scroll或keypress、鼠标的click或者mouseover等事件在触发时,会调用相应的回调函数,如果不断触发,则回调函数的触发频率会非常高,造成一定的资源浪费。
- 防抖函数的作用是,触发事件后延迟一定的时间后再调用相应的回调函数,如果在这个时间内再次或者多次重复触发,则重新计时,即之前本应该执行的回调函数不再执行,从而达到优化的效果。
实现思路
- 入参:首先应该接收一个回调函数fn,(fn即为事件触发后应该执行的那个函数,并且应该在setTimeout里面执行)和希望延迟执行的时间wait
- 所以函数内首先定义一个定时器变量timer,初始值为null;
- 然后返回一个函数,在这个函数里面判断首先判断timer是否存在,如果已经存在(或者说已经被赋值)则说明,事件已经被触发过,此时应当清除此定时器。
- 之后再给timer赋值,在定时器里面执行回调函数(需要重新绑定this和本来的参数)
代码实现
function debounce(fn, wait) {
let timer = null
return function () {
timer ? clearTimeout(timer) : null
timer = setTimeout(function () {
fn.apply(this, arguments)
timer = null
}, wait)
}
}
应用
<!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>
<button id="btn" onclick="handleClick(1)">点击触发</button>
</body>
<script src="./index.js"></script>
<script>
const handleClick = debounce(function (idx) {
console.log("Click!");
}, 1000);
</script>
</html>
优化
有时希望事件触发后立即执行一次,而不是延迟执行,这样的话如果事件不是频繁触发用户可以立即做出得到反馈,有着更好的使用体验。
思路
- 可以添加一个isImmediate参数,用于判断是否需要立即执行
- 定义一个变量isRunOnce判断是否已经执行过一次
- 根据immediate改变setTimeout延迟执行的毫秒数,如果isImmediate为true但是isRunOnce为false时,则delay设置为0
代码实现
function debounce(fn, wait, isImmediate = true) {
let timer = null
let isRunOnce = false
return function () {
let delay = isImmediate && !isRunOnce ? 0 : wait
timer ? clearTimeout(timer) : null
timer = setTimeout(function () {
fn.apply(this, arguments)
timer = null
!isRunOnce ? isRunOnce = true : null
}, delay)
}
}
应用不再举例。