console
function fn1() {
console.log('防抖')
}
function fn2(e) {
console.log('节流', e)
}
function f_debounce(fn, wait) {
let timer = null
if (typeof fn !== 'function') return 'first arguments is not function'
return function () {
if (timer) clearTimeout(timer)
let args = arguments
timer = setTimeout(() => {
fn.apply(this, args)
}, wait)
}
}
function f_throttle(fn, wail) {
let flag = true
if (typeof fn !== 'function') return 'first arguments is not function'
return function () {
let args = arguments
if (!flag) return false
fn.apply(this, args)
flag = false
setTimeout(() => {
flag = true
}, wail)
}
}
(function () {
let j_debounce = document.querySelector('.h_debounce')
let j_throttle = document.querySelector('.h_throttle')
j_debounce.addEventListener('click', f_debounce(fn1, 1000))
j_throttle.addEventListener('click', f_throttle(fn2.bind(null, 2), 1000))
})()
<button class="h_debounce">防抖</button>
<button class="h_throttle">节流</button>