Simplify debounce.md
This commit is contained in:
@ -1,19 +1,16 @@
|
|||||||
### debounce
|
### debounce
|
||||||
|
|
||||||
Creates a debounced function that delays invoking the provided function until after `wait` milliseconds have elapsed since the last time the debounced function was invoked.
|
Creates a debounced function that delays invoking the provided function until at least `ms` milliseconds have elapsed since the last time it was invoked.
|
||||||
|
|
||||||
Use `setTimeout()` and `clearTimeout()` to debounce the given method, `fn`.
|
Each time the supplied function is invoked, clear the current pending timeout with `clearTimeout()` and use `setTimeout()` to create a new timeout that delays invoking the function until at least `ms` milliseconds has elapsed. Use `Function.apply()` to apply the `this` context to the function and provide the necessary arguments.
|
||||||
Use `Function.apply()` to apply the `this` context to the function and provide the necessary `arguments`.
|
Omit the second argument, `ms`, to set the timeout at a default of 0 ms.
|
||||||
Omit the second argument, `wait`, to set the timeout at a default of 0 ms.
|
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const debounce = (fn, wait = 0) => {
|
const debounce = (fn, ms = 0) => {
|
||||||
let inDebounce;
|
let timeoutId;
|
||||||
return function() {
|
return function(...args) {
|
||||||
const context = this,
|
clearTimeout(timeoutId);
|
||||||
args = arguments;
|
timeoutId = setTimeout(() => fn.apply(this, args), ms);
|
||||||
clearTimeout(inDebounce);
|
|
||||||
inDebounce = setTimeout(() => fn.apply(context, args), wait);
|
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
@ -21,7 +18,7 @@ const debounce = (fn, wait = 0) => {
|
|||||||
```js
|
```js
|
||||||
window.addEventListener(
|
window.addEventListener(
|
||||||
'resize',
|
'resize',
|
||||||
debounce(function(evt) {
|
debounce(() => {
|
||||||
console.log(window.innerWidth);
|
console.log(window.innerWidth);
|
||||||
console.log(window.innerHeight);
|
console.log(window.innerHeight);
|
||||||
}, 250)
|
}, 250)
|
||||||
|
|||||||
Reference in New Issue
Block a user