Last active
February 11, 2020 06:35
-
-
Save kazuma1989/1c2b46f26e7f8a37a9a77387bb0b1bdc to your computer and use it in GitHub Desktop.
Simple throttle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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