- Published on
typescript debounce
- Author
- Name
- yceffort
Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since the last time the debounced function was invoked. The debounced function comes with a cancel method to cancel delayed func invocations and a flush method to immediately invoke them. Provide options to indicate whether func should be invoked on the leading and/or trailing edge of the wait timeout. The func is invoked with the last arguments provided to the debounced function. Subsequent calls to the debounced function return the result of the last func invocation.
λλ°μ΄μ€λ κ³Όλ€ν μ΄λ²€νΈ λ‘μ§μ΄ μ€νλλ κ²μ λ°©μ§νλ ν¨μλ‘, νΈμΆμ΄ λ°λ³΅λλ λμμλ λ°λ³΅ν΄μ λ‘μ§μ΄ μ€νλλ κ²μ λ§κ³ , μ€μ ν μκ°μ΄ μ§λκ³ λμμΌ λ‘μ§μ΄ μ€ννκ² νλ ν¨μλ€.
export function debounce<Params extends any[]>(
func: (...args: Params) => any,
timeout: number,
): (...args: Params) => void {
let timer: NodeJS.Timeout
return (...args: Params) => {
clearTimeout(timer)
timer = setTimeout(() => {
func(...args)
}, timeout)
}
}
μ¦, λ°λ³΅λλ μ΄λ²€νΈκ° κ³μν΄μ μ€νλ λ, λ§€λ² κ·Έ μ΄λ²€νΈλ₯Ό μ€ννλ κ²μ΄ μλλΌ, timeout λ§νΌμ μκ°μ΄ νλ₯Έλ€μ, μ΄μ μ μ΄λ²€νΈλ₯Ό 무μνκ³ μ΄λ²€νΈ νλλ§ μ€ννλ κ²μ΄λ€.