(单位:1秒)
function debounce(fn, delay) {
let timer = null
return function () {
if (timer) {
clearTimeout(timer)
}
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)
btnDom.addEventListener('click', debounced)
立即执行版