Refactor debounce and throttle

This commit is contained in:
Jakub Ďuraš 2018-09-30 23:42:11 +02:00 committed by Jordan Eldredge
parent 82a81bf584
commit 6ecc5142b5

View file

@ -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;