Debounce enforces that a function not be called again until a certain amount of time has passed without it being called.
Throttle enforces a maximum number of times a function can be called over time.
Debounce
There are two kinds of debounce: non-immediate execution and immediate execution.
non-immediate execution
It means the function won’t be invoked immediately, but n seconds later. If the function was called in the waiting period, the timer will be reset.
1 | const debounce = (func, delay) => { |
immediate execution
It means the function will be invoked immediately, but it will continue until no more called in n seconds.
1 | const debounce = (func, delay) => { |
Throttle
Date.now()
1 | const throttle = (func, delay) => { |
setTimeout()
1 | const throttle = (func, delay) => { |
Use cases
Debounce:
- search association
- window resize
Throttle:
- click mouse continually
- listen scroll event
References
https://juejin.im/post/5b651dc15188251aa30c8669
https://juejin.im/post/5b8de829f265da43623c4261