单位:2秒
function throttle(fn, delay) {
let timer = null
return function () {
if (!timer) {
timer = setTimeout(() => {
timer = null
fn.apply(this, arguments)
}, delay)
}
}
}
let count = 0
function addCount() {
counterDom.textContent = ++count
}
const counterDom = document.getElementById('counter')
const btnDom = document.getElementById('btn')
const throttled = throttle(addCount, 2000)
btnDom.addEventListener('click', throttled)
综合版-有取消功能