2676. 节流
2025年6月25日小于 1 分钟
2676. 节流
type F = (...args: number[]) => void
function throttle(fn: F, t: number): F {
let lastArgs: number[] = []
let nextRunTime = 0
let timer
return function (...args) {
const now = new Date().getTime()
if (now >= nextRunTime) {
nextRunTime = now + t
fn(...args)
} else {
clearTimeout(timer)
lastArgs = [...args]
timer = setTimeout(() => {
nextRunTime = Date.now() + t
fn(...lastArgs!)
lastArgs = []
timer = null
}, nextRunTime - now)
}
}
}
/**
* const throttled = throttle(console.log, 100);
* throttled("log"); // logged immediately.
* throttled("log"); // logged at t=100ms.
*/