File tree Expand file tree Collapse file tree 1 file changed +7
-20
lines changed
1-js/06-advanced-functions/09-call-apply-decorators/03-debounce Expand file tree Collapse file tree 1 file changed +7
-20
lines changed Original file line number Diff line number Diff line change 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.
You can’t perform that action at this time.
0 commit comments