Last active
April 21, 2022 07:48
-
-
Save DefectingCat/b3717c3305291da89e90c1134c059539 to your computer and use it in GitHub Desktop.
TypeScript Debounce
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
// "typescript": "~4.1.5" | |
type Debounce = { | |
<T extends unknown[]>(fn: (...arg: T) => void | unknown, ms: number): ( | |
this: unknown, | |
...arg: T | |
) => void | unknown; | |
}; | |
/** | |
* debounce function wrapper | |
* | |
* @param {function} fn debounced function | |
* @param {number} ms delay millisecond | |
* @return {function} wrapper | |
* | |
*/ | |
export const debounce: Debounce = (fn, ms) => { | |
let timer: number | null = null; | |
// 需要为this注解类型 | |
return function (...args) { | |
if (timer) clearTimeout(timer); | |
timer = setTimeout(() => { | |
fn.apply(this, args); | |
}, ms); | |
}; | |
}; |
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
type Debounce = { | |
<T extends unknown[], R>(fn: (...arg: T) => R, ms: number): ( | |
this: unknown, | |
...arg: T | |
) => void; | |
}; | |
/** | |
* debounce function wrapper | |
*/ | |
export const debounce: Debounce = (fn, ms) => { | |
let timer: NodeJS.Timer; | |
return function (...args) { | |
clearTimeout(timer); | |
timer = setTimeout(() => { | |
fn.apply(this, args); | |
}, ms); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment