fix debounce
This commit is contained in:
parent
cd5a7e451f
commit
80f2becc95
1 changed files with 7 additions and 20 deletions
|
@ -1,28 +1,15 @@
|
||||||
```js demo
|
```js demo
|
||||||
function debounce(f, ms) {
|
function debounce(func, ms) {
|
||||||
|
let timeout;
|
||||||
let isCooldown = false;
|
|
||||||
|
|
||||||
return function() {
|
return function() {
|
||||||
if (isCooldown) return;
|
clearTimeout(timeout);
|
||||||
|
timeout = setTimeout(() => func.apply(this, arguments), ms);
|
||||||
f.apply(this, arguments);
|
|
||||||
|
|
||||||
isCooldown = true;
|
|
||||||
|
|
||||||
setTimeout(() => isCooldown = false, ms);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
A call to `debounce` returns a wrapper. There may be two states:
|
A call to `debounce` returns a wrapper.
|
||||||
|
|
||||||
- `isCooldown = false` -- ready to run.
|
When called, it schedules the original function call after given `ms` and clears the previous such timeout.
|
||||||
- `isCooldown = true` -- waiting for the timeout.
|
|
||||||
|
|
||||||
In the first call `isCooldown` is falsy, so the call proceeds, and the state changes to `true`.
|
|
||||||
|
|
||||||
While `isCooldown` is true, all other calls are ignored.
|
|
||||||
|
|
||||||
Then `setTimeout` reverts it to `false` after the given delay.
|
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue