-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdebounce.ts
29 lines (21 loc) · 1.03 KB
/
debounce.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
/*
Given a function fn and a time in milliseconds t, return a debounced version of that function.
A debounced function is a function whose execution is delayed by t milliseconds and whose execution is cancelled if it is called again within that window of time. The debounced function should also receive the passed parameters.
For example, let's say t = 50ms, and the function was called at 30ms, 60ms, and 100ms. The first 2 function calls would be cancelled, and the 3rd function call would be executed at 150ms. If instead t = 35ms, The 1st call would be cancelled, the 2nd would be executed at 95ms, and the 3rd would be executed at 135ms.
*/
type F = (...args: number[]) => void;
function debounce(fn: F, t: number): F {
let timeout: ReturnType<typeof setTimeout>;
return function (...args) {
clearTimeout(timeout);
timeout = setTimeout(() => {
fn(...args);
}, t);
};
}
/**
* const log = debounce(console.log, 100);
* log('Hello'); // cancelled
* log('Hello'); // cancelled
* log('Hello'); // Logged at t=100ms
*/