Lesson 5 of 8
Throttling calls
- 14 min
- 6 checks
- 3 hints
- Go to task
Goal
At most one call per interval
Explanation
A mousemove or scroll event fires dozens of times a second, and debouncing is the wrong tool for it: it does nothing as long as the movement keeps going, so anything that follows the pointer freezes until the user stops moving.
Throttling guarantees a steady rhythm. It runs the first call right away, then ignores every call that comes in before the interval is over. Moving the mouse for two seconds fires about 120 events, but with a 100-millisecond interval only about 20 of them run.
Watch out: everything that lands inside the interval is dropped, including the last event. If the last value matters to you, like where the scroll ends up, add one final call after the interval ends, the way lodash's throttle does.
Your task
Write throttle(fn, ms) so it runs the first call right away with its arguments and never runs more than once within ms milliseconds. Then wire the mousemove event on #pad to throttle(track, 100).
Checks
6 checks- throttle returns a function
- The first call runs right away with its arguments
- Calls within the interval run once
- A new call is accepted after the interval
- Continuous movement runs at a steady rhythm
- #pad is wired to a throttled version