单位:2秒
function throttle(fn, delay) {
let last = 0
return function () {
const now = Date.now()
if (now - last > delay) {
fn.apply(this, arguments)
last = now
}
}
}
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)
定时器版