CodeBlanks Logo Icon CodeBlanks

debounce and throttle

Learn debounce and throttle.

debounce and throttle

debounce: waits until the stream goes quiet, then forwards the last element. Used in search boxes to avoid hitting the server on every keystroke.

throttle: forwards at most one element per period, dropping the rest. Ideal for squashing scroll and resize events.

Both exist in the rxdart package as debounceTime and throttleTime. In pure Dart they can be written by hand with timers and asyncExpand.

Simple throttle: take

.take(n) takes the first n elements of a stream and drops the rest. This is the simplest throttle form: a count-based limit instead of time-based.

Example: Stream.fromIterable([1, 2, 3, 4]).take(2) forwards only 1 and 2; 3 and 4 are never produced (lazy stream).

For real time-based throttling use rxdart's throttleTime or a custom timer-based transformer.

Practice Take the first two with take

Make main async. Add var s = Stream.fromIterable([1, 2, 3, 4]);. Add await s.take(2).forEach(print);.

Starter code

main.dart
void main() {
  // make async; build [1,2,3,4] stream; take(2) for first two; print via forEach
}

Sample solution

main.dart
void main() async {
  var s = Stream.fromIterable([1, 2, 3, 4]);
  await s.take(2).forEach(print);
}

Expected output

1
2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the concepts

Term Meaning
debounce Last element after quiet
throttle One element per period
Search box debounce use
Scroll throttle use

2 Which suits a search box?

  • throttle
  • take
  • debounce Correct answer
  • skip

Explanation: debounce sends the last query when the user stops typing.

3 Take the first two

Question
var t = s.____(2);
Answer
var t = s.take(2);

Explanation: take(2) takes the first two elements.

All lessons in Advanced