From 7994a394dc0918dac53ef1835f10dd5c33039a98 Mon Sep 17 00:00:00 2001 From: Forrest Li Date: Mon, 12 Jul 2021 10:53:24 -0400 Subject: [PATCH] feat(macro): Support cancelling debounced calls --- Sources/interfaces.d.ts | 8 ++++++++ Sources/macro.d.ts | 6 ++++-- Sources/macro.js | 6 +++++- 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/Sources/interfaces.d.ts b/Sources/interfaces.d.ts index fed2fb1870b..30260bea9d0 100644 --- a/Sources/interfaces.d.ts +++ b/Sources/interfaces.d.ts @@ -16,6 +16,14 @@ export interface vtkRange { max: number; } +/** + * Represents a debounced function. + */ +export interface vtkDebouncedFunction { + (...args: any) : any; + cancel() : void; +} + export interface vtkOutputPort { filter: vtkAlgorithm; } diff --git a/Sources/macro.d.ts b/Sources/macro.d.ts index bc19ec36e8d..29688dad86e 100644 --- a/Sources/macro.d.ts +++ b/Sources/macro.d.ts @@ -1,4 +1,4 @@ -import { vtkSubscription, vtkProperty, vtkPropertyDomain } from "./interfaces"; +import { vtkSubscription, vtkDebouncedFunction, vtkProperty, vtkPropertyDomain } from "./interfaces"; /** * Allow user to redefine vtkXXXMacro method call. @@ -305,8 +305,10 @@ export function traverseInstanceTree( * @param func * @param wait * @param immediate (default false) + * @returns vtkDebouncedFunction A debounced function that can be called. + * Use .cancel() to clear any pending debounced call. */ -export function debounce(func: (...args: any) => any, wait: number, immediate?: boolean): (...args: any) => any; +export function debounce(func: (...args: any) => any, wait: number, immediate?: boolean): vtkDebouncedFunction; /** * Creates a throttled function that only invokes `func` at most once per diff --git a/Sources/macro.js b/Sources/macro.js index fd797061e74..655d12e4c76 100644 --- a/Sources/macro.js +++ b/Sources/macro.js @@ -985,7 +985,7 @@ export function traverseInstanceTree( export function debounce(func, wait, immediate) { let timeout; - return (...args) => { + const debounced = (...args) => { const context = this; const later = () => { timeout = null; @@ -1000,6 +1000,10 @@ export function debounce(func, wait, immediate) { func.apply(context, args); } }; + + debounced.cancel = () => clearTimeout(timeout); + + return debounced; } // ----------------------------------------------------------------------------