防抖节流
灵感胜于汗水 Lv5

防抖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function debounce(fn, duration = 500) {//自定义防抖函数,默认0.5秒内没有再次触发该函数时执行
let timer
return function (...args) {
timer && clearTimeout(timer)
timer = setTimeout(() => {
typeof fn === 'function' && fn.apply(this, args)
}, duration)
}
}

const input = document.getElementById('input')
input.addEventListener('input', debounce(event => {
console.log(event.target.value)
}));

节流

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function throttle(fn, duration = 1000) { //自定义节流函数,1秒内只触发一次
let time = 0
return function (...args) {
if (new Date() - time > duration) {
typeof fn === 'function' && fn.apply(this, args)
time = new Date()
}
}
}

const btn = document.getElementById('btn')
btn.addEventListener('click', throttle(event => {
console.log(event.target.innerText)
}));
  • 本文标题:防抖节流
  • 本文作者:灵感胜于汗水
  • 创建时间:2022-03-09 14:58:35
  • 本文链接:https://cjhsyc.github.io/2022/03/09/防抖节流/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!