(单位:1秒)
function debounce(fn, delay, immediate) {
let timer = null
return function () {
if (timer) {
clearTimeout(timer)
}
if (immediate) {
let callNow = !timer
timer = setTimeout(() => {
timer = null
}, delay)
if (callNow) {
fn.apply(this, arguments)
}
} else {
timer = setTimeout(() => {
fn.apply(this, arguments)
}, delay)
}
}
}
let count = 0
function addCount() {
counterDom.textContent = ++count
}
const counterDom = document.getElementById('counter')
const btnDom = document.getElementById('btn')
const debounced = debounce(addCount, 1000, true)
btnDom.addEventListener('click', debounced)
有取消功能版