1 | # debounce
|
2 |
|
3 | > Delay function calls until a set time elapses after the last invocation
|
4 |
|
5 | ## Install
|
6 |
|
7 | ```sh
|
8 | npm install debounce
|
9 | ```
|
10 |
|
11 | ## Usage
|
12 |
|
13 | ```js
|
14 | import debounce from 'debounce';
|
15 |
|
16 | function resize() {
|
17 | console.log('height', window.innerHeight);
|
18 | console.log('width', window.innerWidth);
|
19 | }
|
20 |
|
21 | window.onresize = debounce(resize, 200);
|
22 | ```
|
23 |
|
24 | *(You can also use `const debounce = require('debounce')`)*
|
25 |
|
26 | To later clear the timer and cancel currently scheduled executions:
|
27 |
|
28 | ```js
|
29 | window.onresize.clear();
|
30 | ```
|
31 |
|
32 | To execute any pending invocations and reset the timer:
|
33 |
|
34 | ```js
|
35 | window.onresize.flush();
|
36 | ```
|
37 |
|
38 | ## API
|
39 |
|
40 | ### debounce(fn, wait, options?)
|
41 |
|
42 | Creates a debounced function that delays execution until `wait` milliseconds have passed since its last invocation.
|
43 |
|
44 | Set the `immediate` option to `true` to invoke the function immediately at the start of the `wait` interval, preventing issues such as double-clicks on a button.
|
45 |
|
46 | The returned function has a `.clear()` method to cancel scheduled executions, and a `.flush()` method for immediate execution and resetting the timer for future calls.
|
47 |
|
48 | ## Related
|
49 |
|
50 | - [p-debounce](https://github.com/sindresorhus/p-debounce) - Similar but handles promises.
|