Skip to content

Commit

Permalink
feat(macro): Support cancelling debounced calls
Browse files Browse the repository at this point in the history
  • Loading branch information
floryst committed Jul 13, 2021
1 parent fb63f20 commit 7994a39
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 3 deletions.
8 changes: 8 additions & 0 deletions Sources/interfaces.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
6 changes: 4 additions & 2 deletions Sources/macro.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { vtkSubscription, vtkProperty, vtkPropertyDomain } from "./interfaces";
import { vtkSubscription, vtkDebouncedFunction, vtkProperty, vtkPropertyDomain } from "./interfaces";

/**
* Allow user to redefine vtkXXXMacro method call.
Expand Down Expand Up @@ -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
Expand Down
6 changes: 5 additions & 1 deletion Sources/macro.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -1000,6 +1000,10 @@ export function debounce(func, wait, immediate) {
func.apply(context, args);
}
};

debounced.cancel = () => clearTimeout(timeout);

return debounced;
}

// ----------------------------------------------------------------------------
Expand Down

0 comments on commit 7994a39

Please sign in to comment.