UNPKG

1.19 kBMarkdownView Raw
1# debounce
2
3> Delay function calls until a set time elapses after the last invocation
4
5## Install
6
7```sh
8npm install debounce
9```
10
11## Usage
12
13```js
14import debounce from 'debounce';
15
16function resize() {
17 console.log('height', window.innerHeight);
18 console.log('width', window.innerWidth);
19}
20
21window.onresize = debounce(resize, 200);
22```
23
24*(You can also use `const debounce = require('debounce')`)*
25
26To later clear the timer and cancel currently scheduled executions:
27
28```js
29window.onresize.clear();
30```
31
32To execute any pending invocations and reset the timer:
33
34```js
35window.onresize.flush();
36```
37
38## API
39
40### debounce(fn, wait, options?)
41
42Creates a debounced function that delays execution until `wait` milliseconds have passed since its last invocation.
43
44Set 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
46The 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.