Throttle and Debounce
Whenever I need to use throttle or debounce I have to remind myself of the differences. Here are a few definitions as a reminder.
Throttle
Creates a throttled function that only invokes func at most once per every wait milliseconds.
lodash throttle
Throttling enforces a maximum number of times a function can be called over time. As in “execute this function at most once every 100 milliseconds”.
CSS-TRICKS
Debounce
Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since the last time the debounced function was invoked.
lodash debounce
Debouncing enforces that a function not be called again until a certain amount of time has passed without it being called. As in “execute this function only if 100 milliseconds have passed without it being called”.
CSS-TRICKS
Demo
Use left and right arrow keys to navigate and see the different behaviours of throttle and debounce.
- press left/right keys
- press and hold left/right keys
Throttled
- 0
- 1
- 2
- 3
- 4
- 5
- 6
- 7
Debounced
- 0
- 1
- 2
- 3
- 4
- 5
- 6
- 7
You can also see this example and code in the svelte repl.