Skip to content

Commit

Permalink
feat(util): debounce support cancel
Browse files Browse the repository at this point in the history
  • Loading branch information
Gggpound committed Jun 4, 2024
1 parent 754fad2 commit a404108
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 deletions packages/core/src/shared/debounce.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,9 @@

type debounceFn<T extends (...args: any[]) => any> = (this: ThisParameterType<T>, ...args: Parameters<T>) => void;

export function debounce<T extends (...args: any[]) => any>(func: T, wait: number): debounceFn<T> {
export function debounce<T extends (...args: any[]) => any>(func: T, wait: number) {
let timeout: NodeJS.Timeout | null;

return function (this: ThisParameterType<T>, ...args: Parameters<T>) {
function run(this: ThisParameterType<T>, ...args: Parameters<T>) {
const context = this;

const later = function () {
Expand All @@ -29,5 +28,13 @@ export function debounce<T extends (...args: any[]) => any>(func: T, wait: numbe

clearTimeout(timeout as NodeJS.Timeout);
timeout = setTimeout(later, wait);
};
}
Object.defineProperty(run, 'cancel', {
value: () => {
clearTimeout(timeout as NodeJS.Timeout);
},
enumerable: false,
writable: false,
});
return run as debounceFn<T> & { cancel: () => void };
}

0 comments on commit a404108

Please sign in to comment.