Lesson 5 of 8

Throttling calls

Goal

At most one call per interval

01

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.

02

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
  1. throttle returns a function
  2. The first call runs right away with its arguments
  3. Calls within the interval run once
  4. A new call is accepted after the interval
  5. Continuous movement runs at a steady rhythm
  6. #pad is wired to a throttled version
03

Hints

0/3
Track lessons0 of 8 done

Find out where your page really loses time, and how to win it back by adding elements in one go, making fewer calls and never computing the same thing twice.

Advanced level, 8 lessons, 1.5 hours in total.

index.html
Preview
index.html100%
–/6

Press “Run and check” to grade your code.

6 checks listed under “Your task”.

Track lessons0 of 8 done

Find out where your page really loses time, and how to win it back by adding elements in one go, making fewer calls and never computing the same thing twice.

Advanced level, 8 lessons, 1.5 hours in total.