Skip to content

Instantly share code, notes, and snippets.

@kazuma1989
Last active February 11, 2020 06:35
Show Gist options
  • Save kazuma1989/1c2b46f26e7f8a37a9a77387bb0b1bdc to your computer and use it in GitHub Desktop.
Save kazuma1989/1c2b46f26e7f8a37a9a77387bb0b1bdc to your computer and use it in GitHub Desktop.
Simple throttle
export function throttle<A extends unknown[]>(
func: (...args: A) => unknown,
wait = 0,
): (...args: A) => void {
// Fire the first call immediately
let prevTime = Date.now() - wait
// Fire trailing calls after wait
let trailingCall: ReturnType<typeof setTimeout>
return function throttled(...args: A) {
clearTimeout(trailingCall)
const currentTime = Date.now()
const remaining = wait - (currentTime - prevTime)
if (remaining > 0) {
trailingCall = setTimeout(() => func(...args), remaining)
return
}
prevTime = currentTime
func(...args)
}
}
export function throttle<A extends unknown[]>(
func: (...args: A) => unknown,
wait = 0,
): (...args: A) => void {
// Fire immediately
let prevTime = Date.now() - wait
return function throttled(...args: A) {
const currentTime = Date.now()
if (currentTime - prevTime < wait) return
prevTime = currentTime
func(...args)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment