mirror of
https://github.com/captbaritone/webamp.git
synced 2026-07-26 03:24:18 +00:00
Refactor debounce and throttle
This commit is contained in:
parent
82a81bf584
commit
6ecc5142b5
1 changed files with 19 additions and 16 deletions
35
js/utils.ts
35
js/utils.ts
|
|
@ -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;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue