diff --git a/1-js/06-advanced-functions/09-call-apply-decorators/03-debounce/solution.md b/1-js/06-advanced-functions/09-call-apply-decorators/03-debounce/solution.md index 4f5867de..a2d34619 100644 --- a/1-js/06-advanced-functions/09-call-apply-decorators/03-debounce/solution.md +++ b/1-js/06-advanced-functions/09-call-apply-decorators/03-debounce/solution.md @@ -1,28 +1,15 @@ ```js demo -function debounce(f, ms) { - - let isCooldown = false; - +function debounce(func, ms) { + let timeout; return function() { - if (isCooldown) return; - - f.apply(this, arguments); - - isCooldown = true; - - setTimeout(() => isCooldown = false, ms); + clearTimeout(timeout); + timeout = setTimeout(() => func.apply(this, arguments), 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. -- `isCooldown = true` -- waiting for the timeout. +When called, it schedules the original function call after given `ms` and clears the previous such 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.