forked from Tinkoff/utils.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdebounce.ts
More file actions
28 lines (24 loc) · 875 Bytes
/
debounce.ts
File metadata and controls
28 lines (24 loc) · 875 Bytes
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
import curryN from './curryN';
import { debounce } from '../typings/types';
/**
* Creates a debounced function that delays invoking `func` until after `wait`
* milliseconds have elapsed since the last time the debounced function was
* invoked. Delayed function invocation might be cancelled by calling cancel method.
*
* @param {number} wait The number of milliseconds to delay.
* @param {Function} fn The function to debounce.
* @returns {Function} Returns the new debounced function.
*/
export default curryN(2, (wait, fn) => {
let timeout;
function f() {
let args = arguments;
clearTimeout(timeout);
timeout = setTimeout(
() => fn.apply(this, args), // eslint-disable-line prefer-rest-params
wait
);
}
(f as any).cancel = () => clearTimeout(timeout);
return f;
}) as typeof debounce