防抖函数
概念
所谓防抖,就是指触发事件 N 秒后才执行函数,如果在 N 秒内又触发了事件,则会重新计算函数执行时间,也就是说,最后一次触发事件后的N秒后执行函数
实现
<button class="debounceButton">防抖事件</button>
<script>
// 获取防抖事件按钮
const debounceButton = document.querySelector('.debounceButton');
// 分装防抖函数
function debounce (debounceCb, delay = 1000) {
let timer;
return (...args) => {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
debounceCb.apply(this.args)
}, delay)
}
};
// 调用防抖函数
debounceButton.addEventListener('click', debounce(e => {
console.log('防抖事件');
}))
</script>
节流函数
概念
所谓节流,就是指连续触发事件但是在 N 秒中只执行一次函数,也就是说,在触发事件后,不管你触发了多少次,它都是在每 N 秒执行一次
实现
<button class="throttleButton">节流事件</button>
<srcipt>
// 获取节流事件按钮
const throttleButton = document.querySelector('.throttleButton');
// 封装节流函数
function debounce (debounceCb, delay = 1000) {
let timer;
return (...args) => {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
debounceCb.apply(this.args)
}, delay)
}
};
// 调用节流函数
throttleButton.addEventListener('click', throttle(e => {
console.log('节流事件')
}))
</srcipt>