单位:8秒 点击“取消节流”按钮后,再点击“点击这里”按钮,可立即触发事件
function throttle(fn, delay) {
let timer = null
let prev = 0
let throttled = function () {
let now = +new Date()
let remaining = delay - (now - prev)
// 如果没有剩余的时间了或者你改了系统时间
if (remaining <= 0 || remaining > delay) {
if (timer) {
clearTimeout(timer)
timer = null
}
prev = now
fn.apply(this, arguments)
} else if (!timer) {
timer = setTimeout(() => {
prev = +new Date()
timer = null
fn.apply(this, arguments)
}, remaining)
}
}
throttled.cancel = function () {
clearTimeout(timer)
timer = null
prev = 0
}
return throttled
}
let count = 0
function addCount() {
counterDom.textContent = ++count
}
const counterDom = document.getElementById('counter')
const btnDom = document.getElementById('btn')
const throttled = throttle(addCount, 1000 * 8)
btnDom.addEventListener('click', throttled)