Skip to content

Commit

Permalink
Refactor debounce and throttle
Browse files Browse the repository at this point in the history
  • Loading branch information
durasj authored and captbaritone committed Oct 1, 2018
1 parent 82a81bf commit 6ecc514
Showing 1 changed file with 19 additions and 16 deletions.
35 changes: 19 additions & 16 deletions js/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -255,34 +255,37 @@ export function spliceIn<T>(original: T[], start: number, newValues: T[]): T[] {
return newArr;
}

type Procedure = (...args: any[]) => void;
export function debounce(func: Function, delay: number): Function {
let timeout: number;
let callbackArgs: any[] = [];

export function debounce<F extends Procedure>(func: F, delay: number): F {
let token: NodeJS.Timer;
return function(this: any, ...args: any[]): void {
if (token != null) {
clearTimeout(token);
return function(context: Object, ...args: any[]): void {
callbackArgs = args;

if (timeout != null) {
clearTimeout(timeout);
}
token = setTimeout(() => {
func.apply(this, args);
timeout = window.setTimeout(() => {
func.apply(context, callbackArgs);
}, delay);
} as any;
};
}

// Trailing edge only throttle
export function throttle<F extends Procedure>(func: F, delay: number): F {
let timeout: NodeJS.Timer | null = null;
let callbackArgs: any[] | null = null;
export function throttle(func: Function, delay: number): Function {
let timeout: number | null = null;
let callbackArgs: any[] = [];

return function(this: any, ...args: any[]): void {
return function(context: Object, ...args: any[]): void {
callbackArgs = args;

if (!timeout) {
timeout = setTimeout(() => {
func.apply(this, callbackArgs);
timeout = window.setTimeout(() => {
func.apply(context, callbackArgs);
timeout = null;
}, delay);
}
} as any;
};
}

let counter = 0;
Expand Down

0 comments on commit 6ecc514

Please sign in to comment.