From 6ecc5142b55bd1674fc7c227bdfa2e4064f4862b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20=C4=8Eura=C5=A1?= Date: Sun, 30 Sep 2018 23:42:11 +0200 Subject: [PATCH] Refactor debounce and throttle --- js/utils.ts | 35 +++++++++++++++++++---------------- 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/js/utils.ts b/js/utils.ts index daf3eaf3..4231e0a5 100644 --- a/js/utils.ts +++ b/js/utils.ts @@ -255,34 +255,37 @@ export function spliceIn(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(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(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;