Skip to content

Instantly share code, notes, and snippets.

@DefectingCat
Last active April 21, 2022 07:48
Show Gist options
  • Save DefectingCat/b3717c3305291da89e90c1134c059539 to your computer and use it in GitHub Desktop.
Save DefectingCat/b3717c3305291da89e90c1134c059539 to your computer and use it in GitHub Desktop.
TypeScript Debounce
// "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);
};
};
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