/
delay.ts
37 lines (30 loc) · 1002 Bytes
/
delay.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
/**
* @module utils/delay
*/
/* globals setTimeout, clearTimeout */
/**
* Returns a function wrapper that will trigger a function after a specified wait time.
* The timeout can be canceled by calling the cancel function on the returned wrapped function.
*
* @param func The function to wrap.
* @param wait The timeout in ms.
*/
export default function delay<T extends ( ...args: Array<any> ) => any>( func: T, wait: number ): DelayedFunc<T> {
let timer: ReturnType<typeof setTimeout>;
function delayed( ...args: Parameters<T> ) {
delayed.cancel();
timer = setTimeout( () => func( ...args ), wait );
}
delayed.cancel = () => {
clearTimeout( timer );
};
return delayed;
}
export interface DelayedFunc<T extends ( ...args: Array<any> ) => any> {
( ...args: Parameters<T> ): void;
cancel(): void;
}