In above, isThrottled = false assignment is done inside setTimeout callback. However, only one callback is pushed into task queue and it isn't executed until stack is empty (for loop has to be completed).
isThrottled is always true => setTimeout isn't called => one callback (that was registered for initial false isThrottled) => cb executed at end and outputs last value => output: 1, 9999999.
Original code: https://javascript.info/call-apply-decorators#throttle-decorator
Here's a small code snippet to show where it doesn't work.
Expected Output
1, 249204, 452039, ... , 9999999 (These are random increasing numbers)
Output
1, 9999999
Why does it fail?
In above,
isThrottled = false
assignment is done insidesetTimeout
callback. However, only one callback is pushed into task queue and it isn't executed until stack is empty (for loop has to be completed).isThrottled
is alwaystrue
=>setTimeout
isn't called => one callback (that was registered for initial falseisThrottled
) => cb executed at end and outputs last value => output: 1, 9999999.Correct Solution: https://github.com/javascript-tutorial/en.javascript.info/pull/2844
This PR giving an alternative solution.