Skip to content

Commit 80f2bec

Browse files
committed
fix debounce
1 parent cd5a7e4 commit 80f2bec

File tree

1 file changed

+7
-20
lines changed
  • 1-js/06-advanced-functions/09-call-apply-decorators/03-debounce

1 file changed

+7
-20
lines changed
Lines changed: 7 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,15 @@
11
```js demo
2-
function debounce(f, ms) {
3-
4-
let isCooldown = false;
5-
2+
function debounce(func, ms) {
3+
let timeout;
64
return function() {
7-
if (isCooldown) return;
8-
9-
f.apply(this, arguments);
10-
11-
isCooldown = true;
12-
13-
setTimeout(() => isCooldown = false, ms);
5+
clearTimeout(timeout);
6+
timeout = setTimeout(() => func.apply(this, arguments), ms);
147
};
15-
168
}
17-
```
189

19-
A call to `debounce` returns a wrapper. There may be two states:
20-
21-
- `isCooldown = false` -- ready to run.
22-
- `isCooldown = true` -- waiting for the timeout.
10+
```
2311

24-
In the first call `isCooldown` is falsy, so the call proceeds, and the state changes to `true`.
12+
A call to `debounce` returns a wrapper.
2513

26-
While `isCooldown` is true, all other calls are ignored.
14+
When called, it schedules the original function call after given `ms` and clears the previous such timeout.
2715

28-
Then `setTimeout` reverts it to `false` after the given delay.

0 commit comments

Comments
 (0)