| | |

RxJS 06 ๐ŸŸฃ Rate Limiting & Time Operators โ€” Controlling high-frequency events with debounceTime, throttleTime, auditTime, and delay

โฑ๏ธ Estimated read: 22 min | |

RxJS time-based operators all take a number of milliseconds, and they all return an observable that emits later than the source. Beyond that they agree on almost nothing. debounceTime waits for silence, throttleTime opens a fixed window and keeps the first value, auditTime opens the same window and keeps the last value, and delay keeps every value and only moves it forward in time. Choosing the wrong one is the difference between a search box that fires one request and one that fires forty, or a scroll handler that forces a layout sixty times per second.

The confusion comes from the fact that all four are described as “rate limiting,” and all four look identical on a slow test. The differences only surface when the source is dense. A mousemove stream fires between 60 and 1000 times per second depending on the pointer’s polling rate. A scroll stream on a trackpad fires continuously with no gap at all. An input stream fires once every 80 to 100 ms for a fast typist. Under that load the four operators produce visibly different output, and picking the wrong one produces either a flood downstream or a UI that never updates.

This chapter covers the four operators named in the title plus their close relatives sampleTime and delayWhen, which share the same underlying model of a time window. It starts with why the family exists and what problem each member solves, then walks through the timing rules of each operator, then assembles a session that runs the same source through all of them so the difference is visible side by side.

Key point: debounceTime, throttleTime, and auditTime are all lossy โ€” they decide which values survive and which are thrown away โ€” while delay is lossless and only shifts every value forward in time. The operator you want is determined by whether you need the last value of a burst (debounceTime), the first value of a window (throttleTime), the last value of a window (auditTime), or all values, later (delay).


Why rate limiting operators exist

The firehose problem. A DOM event stream is not a list of discrete user actions; it is a sample of the browser’s event loop. mousemove fires on every pointer position the browser reports, which on a high-polling-rate mouse exceeds 1000 events per second. scroll fires on every scroll position change. input fires on every keystroke. A subscriber that does work proportional to the number of events is doing work proportional to the sampling rate, not to the user’s intent. The user typed eight characters; the intent was one search.

The cost of a downstream effect. The rate that matters is not the event rate, it is the rate of the expensive thing at the end of the pipe. A console.log tolerates a thousand calls per second. A fetch does not: each one opens a connection, browsers cap concurrent connections per origin at six, and a burst of forty requests queues thirty-four of them while the first eleven responses are already stale by the time they land. The operator exists so the cost of the pipe is controlled at the pipe rather than at every subscriber.

Which value, not how many. The naive fix โ€” “take every Nth value” โ€” is wrong because the interesting value is not at a fixed position. In a burst of keystrokes the interesting value is the last one, because it reflects the final text. In a burst of scroll events the interesting value is the first one, because the handler is going to read the current position anyway when it runs. In a burst of pointer positions the interesting value is the last one in each window, because that is where the cursor actually is. The operator family is therefore parameterised by which value survives, not just by how much is dropped.

The window has two edges. Every rate limiter here defines a window in time and picks a value out of it. The window can be anchored at the first value (throttle, audit) or restarted at the last value (debounce). The value can be delivered at the leading edge, the trailing edge, or both. Those two choices โ€” anchor and edge โ€” produce the four distinct behaviours, and the operators in this chapter are named for the combinations.

Time is a resource that can be spent, not just cut. Sometimes nothing should be dropped. A replay of recorded events, a delayed notification, a staged entrance animation: every value is meaningful, it just needs to arrive later than it was produced. delay and delayWhen are the operators for that, and they are lossless by construction. Losing a value there is a bug, not a feature.

The latency trade-off. Any rate limiter introduces delay by definition. throttleTime(200) means a user action can take up to 200 ms to become visible; debounceTime(300) means it takes 300 ms after the user stops. Both are perceptible. The design question is never “how do I drop the most events” but “how much latency can this interaction afford,” and the operator encodes that answer.


a. debounceTime โ€” the quiet-period operator

debounceTime(dueTime, scheduler?) emits the most recent value from the source, but only after dueTime milliseconds have passed without the source emitting again. Every value restarts the timer. If the source never goes quiet for dueTime, the operator never emits at all. The consequence is that debounceTime is about the end of a burst, and its output is the last value of that burst.

import { fromEvent, map, debounceTime, distinctUntilChanged } from 'rxjs';

const search = document.querySelector<HTMLInputElement>('#search')!;

fromEvent(search, 'input')
  .pipe(
    // 1. Pull the current text out of every input event
    map(() => search.value),
    // 2. Wait until 300 ms pass with no further keystroke
    debounceTime(300),
    // 3. Drop the value if it equals the previous emitted value
    distinctUntilChanged()
  )
  .subscribe((term) => {
    // Fires once per settled term, not once per keystroke
    console.log('query:', term);
  });

Typing rxjs at 100 ms per keystroke produces five input events and zero output while typing, then a single output of rxjs 300 ms after the x. Deleting back to rx produces a single output of rx. The distinctUntilChanged is the second half of the pattern: debounceTime collapses within a burst, distinctUntilChanged collapses across bursts.

The order between the two matters. If distinctUntilChanged sits before debounceTime, a repeated value is dropped and never reaches the debounce timer, so the timer is not restarted. The operator then fires on its original schedule with a value the user has already moved past. Placing it after is the correct order.

Two notification behaviours are worth memorising. When the source completes, debounceTime emits any pending value immediately rather than waiting out the timer, so a finite source such as of(1, 2, 3) does not lose its last value. When the source errors, the pending value is discarded and the error propagates straight through.

debounceTime is the wrong operator for a stream that never has a gap. A scroll stream on a trackpad has no silence, so the timer restarts forever and nothing is emitted until the user stops scrolling entirely. The visible result is a UI that freezes and then jumps.

The general form is debounce(durationSelector), which returns an observable defining the quiet period per value. That allows a variable delay โ€” longer for a slow typist, shorter for a fast one โ€” but the reset semantics are identical.

import { of, timer, debounce } from 'rxjs';

of('a', 'b', 'c')
  .pipe(
    // Quiet period is derived per value: 100ms, then 200ms, then 300ms
    debounce((value, index) => timer((index + 1) * 100))
  )
  .subscribe(console.log);

b. throttleTime โ€” the leading-edge window

throttleTime(duration, scheduler?, config?) emits a value, then ignores everything for duration milliseconds, then repeats. The window is anchored at the value that was emitted and is never restarted by incoming values. Given a continuous source, throttleTime produces a steady stream at roughly 1/duration hertz.

The config parameter is ThrottleConfig, an object with leading and trailing booleans that defaults to { leading: true, trailing: false }.

import { fromEvent, throttleTime, map } from 'rxjs';

fromEvent(window, 'scroll', { passive: true })
  .pipe(
    // Emit at most once every 200 ms; leading only (the default)
    throttleTime(200, undefined, { leading: true, trailing: false }),
    map(() => window.scrollY)
  )
  .subscribe((y) => {
    // Reading scrollY here happens at most 5 times per second
    console.log(y);
  });

The two flags produce four combinations, and three of them are useful.

{ leading: true, trailing: false } is the default: the first value of each window gets through, everything after it is dropped until the window closes. This is the “act immediately, then ignore” behaviour, and it is what you want for a scroll handler that must feel instant.

{ leading: true, trailing: true } emits the first value of the window and also the last value received during that window, then starts a fresh window. This is the “act immediately and also catch the final position” behaviour. For scroll it means the handler runs on the first event and again when scrolling stops, so the final position is always rendered and the page never rests one frame short.

{ leading: false, trailing: true } drops the first value and emits only the last value received at the end of the window. This is behaviourally identical to auditTime, described next.

{ leading: false, trailing: false } never emits anything and exists only to complete the matrix.

import { fromEvent, throttleTime, map } from 'rxjs';

fromEvent<MouseEvent>(document, 'mousemove')
  .pipe(
    // Emit the first event, then once more when the 100 ms window ends
    throttleTime(100, undefined, { leading: true, trailing: true }),
    map((event) => ({ x: event.clientX, y: event.clientY }))
  )
  .subscribe((position) => renderCursor(position));

The general form throttle(durationSelector, config) replaces the fixed timer with an observable. The window closes on the selector’s first emission or its completion, which is how you express “throttle until this operation finishes” rather than “throttle for 200 ms.”

import { fromEvent, throttle, timer } from 'rxjs';

const refresh = document.querySelector<HTMLButtonElement>('#refresh')!;

fromEvent(refresh, 'click')
  .pipe(
    // Window lasts until the inner observable emits; here a variable delay
    throttle(() => timer(1000))
  )
  .subscribe(() => reload());

c. auditTime and sampleTime โ€” the trailing edge

auditTime(duration, scheduler?) ignores values for duration milliseconds after a value arrives, then emits the most recent value received during that period. Unlike debounceTime, the timer is not restarted by subsequent values โ€” it always runs the full duration. Unlike throttleTime, the emitted value is the last one in the window, not the first.

The mental model is one word: debounceTime resets, auditTime does not. That single difference decides which one to use. debounceTime produces nothing until silence; auditTime produces a value on a fixed cadence as long as the source keeps emitting.

import { fromEvent, auditTime, map } from 'rxjs';

// A value is delivered every 100 ms, carrying the latest cursor position
fromEvent<MouseEvent>(document, 'mousemove')
  .pipe(
    auditTime(100),
    map((event) => ({ x: event.clientX, y: event.clientY }))
  )
  .subscribe((pos) => {
    // Called ~10 times per second while moving, never while idle
    updateTrail(pos);
  });

throttleTime(duration, undefined, { leading: false, trailing: true }) is behaviourally identical to auditTime(duration); the two share an implementation. The named operator exists because the intent is clearer and because the config form is easy to get wrong.

sampleTime(period, scheduler?) is the third member of the family, and it changes which clock is in charge. Where auditTime starts its timer when a value arrives, sampleTime runs a clock of its own at a fixed period, independent of the source. At each tick it emits the most recent value โ€” but only if a new value has arrived since the previous sample. If the source is idle across a tick, nothing is emitted for that tick.

import { interval, sampleTime, scan, take } from 'rxjs';

// A counter that produces a value every 10 ms
interval(10)
  .pipe(
    scan((n) => n + 1, 0),
    // Sample it on a fixed 250 ms grid; emits the latest counter value
    sampleTime(250),
    take(4)
  )
  .subscribe((n) => console.log('sampled:', n));

The output is roughly 25, 50, 75, 100 โ€” the counter’s value at each tick, not every counter value. sampleTime is the operator for turning a dense sensor stream into a fixed-rate series suitable for a chart axis, because the output rate is guaranteed by the period rather than by the source’s behaviour.


d. delay and delayWhen โ€” shifting, not dropping

Everything so far is lossy. delay(due, scheduler?) is not. It subscribes to the source, stores every notification, and replays each one due milliseconds after it arrived. No value is dropped and no value is merged with another; the entire sequence is translated in time while keeping its internal spacing.

import { of, delay } from 'rxjs';

of('a', 'b', 'c')
  .pipe(
    // The three values arrive at ~1000ms, ~1001ms, ~1002ms
    delay(1000)
  )
  .subscribe((value) => console.log(value));

Three properties are worth knowing before reaching for it.

It buffers. delay keeps every pending value in memory until its scheduled time arrives. A source emitting 10,000 values per second with a delay(10_000) holds 100,000 values. It is not a tool for flattening a high-frequency stream; it is a tool for shifting a modest one.

Errors are not delayed. In RxJS 7, an error notification passes through delay immediately and abandons the queued values. This is deliberate: an error in the source means the queued values may no longer be valid, so presenting them after the error would be worse than dropping them.

Completion is delayed. The complete notification is held until the last queued value has been emitted. A delay(1000) on a three-value source that completes immediately still emits all three values before completing.

delayWhen(delayDurationSelector, subscriptionDelay?) is the general form, and it is the one that makes the idea interesting. The selector receives each value and its index and returns an observable whose first emission closes that value’s delay individually, so different values can be delayed by different amounts or by different clocks.

import { from, timer, delayWhen } from 'rxjs';

from(['step-1', 'step-2', 'step-3'])
  .pipe(
    // Value i is delayed by i * 400ms, producing a staged sequence
    delayWhen((value, index) => timer(index * 400))
  )
  .subscribe((value) => console.log(value));

The second argument, subscriptionDelay, delays the subscription to the source rather than the values. That is how you express “start this pipeline in two seconds” without an extra timer race.

import { of, timer, delayWhen } from 'rxjs';

of(1, 2, 3)
  .pipe(
    // Source is not even subscribed until 2000 ms have passed
    delayWhen(() => timer(0), timer(2000))
  )
  .subscribe(console.log);

A useful contrast closes the section. debounceTime(0) and delay(0) are not interchangeable. A synchronous of(1, 2, 3) piped through debounceTime(0) emits only 3, because the scheduler is asynchronous and every value restarts the timer before it can fire. The same source piped through delay(0) emits all three, because nothing is collapsed. That is the lossless/lossy distinction in its purest form.


Complete Example Session

// ============================================
// PART 1: IMPORTS AND SHARED ELEMENTS
// ============================================
import { fromEvent, Subject, of, merge, timer, interval } from 'rxjs';
import {
  map, scan, take, filter, switchMap,
  debounceTime, throttleTime, auditTime, sampleTime,
  delay, delayWhen, distinctUntilChanged
} from 'rxjs/operators';

const searchEl = document.querySelector<HTMLInputElement>('#search')!;
const headerEl = document.querySelector<HTMLElement>('#header')!;
const dotEl = document.querySelector<HTMLElement>('#dot')!;

// ============================================
// PART 2: THE SEARCH BOX (debounceTime)
// ============================================
const suggestions$ = fromEvent(searchEl, 'input').pipe(
  map(() => searchEl.value.trim()),   // current text on every keystroke
  debounceTime(300),                  // wait for 300ms of silence
  distinctUntilChanged(),             // ignore repeats across bursts
  switchMap((term) =>
    term.length < 2
      ? of([])                        // too short: emit an empty list
      : fetchSuggestions(term)        // one request per settled term
  )
);

suggestions$.subscribe((items) => renderSuggestions(items));

// ============================================
// PART 3: THE HEADER (throttleTime, leading)
// ============================================
fromEvent(window, 'scroll', { passive: true })
  .pipe(
    throttleTime(100, undefined, { leading: true, trailing: false }),
    map(() => window.scrollY)
  )
  .subscribe((y) => {
    // Runs at most 10x/sec, immediately on the first event
    headerEl.classList.toggle('compact', y > 80);
  });

// ============================================
// PART 4: THE FINAL POSITION (throttleTime, trailing)
// ============================================
fromEvent(window, 'scroll', { passive: true })
  .pipe(
    // First event renders immediately; the last event of the window
    // also renders, so the parallax never stops one frame short
    throttleTime(100, undefined, { leading: true, trailing: true }),
    map(() => window.scrollY),
    distinctUntilChanged()            // trailing can repeat the leading value
  )
  .subscribe((y) => {
    document.documentElement.style.setProperty('--parallax', `${y * -0.2}px`);
  });

// ============================================
// PART 5: THE CURSOR TRAIL (auditTime)
// ============================================
fromEvent<MouseEvent>(document, 'mousemove')
  .pipe(
    auditTime(50),                    // emit the LAST position of each window
    map((e) => ({ x: e.clientX, y: e.clientY }))
  )
  .subscribe(({ x, y }) => {
    dotEl.style.transform = `translate(${x}px, ${y}px)`;
  });

// ============================================
// PART 6: THE GAUGE (sampleTime)
// ============================================
interval(16)                          // ~60 Hz source
  .pipe(
    scan((n) => n + 1, 0),            // running counter
    sampleTime(250),                  // keep only the value on the 250ms grid
    take(8)                           // stop after eight samples
  )
  .subscribe((n) => drawGauge(n));

// ============================================
// PART 7: THE DELAYED NOTICE (delay)
// ============================================
const errors$ = new Subject<string>();

errors$
  .pipe(
    // Every error is shown 400ms after it happened. This is lossless:
    // a retry that succeeds in 400ms still shows the banner. If you
    // want suppression, that is debounceTime, not delay.
    delay(400)
  )
  .subscribe((message) => showBanner(message));

// ============================================
// PART 8: THE STAGGER (delayWhen)
// ============================================
from(['card-1', 'card-2', 'card-3', 'card-4'])
  .pipe(
    // Each card starts 120ms after the previous one
    delayWhen((id, index) => timer(index * 120))
  )
  .subscribe((id) => {
    document.getElementById(id)!.classList.add('enter');
  });

// ============================================
// PART 9: SIDE BY SIDE ON ONE SOURCE
// ============================================
// A source that emits 0..9 at 40ms intervals, then completes at 400ms
const dense$ = interval(40).pipe(take(10));

dense$.pipe(debounceTime(100)).subscribe((v) => console.log('debounce', v));
dense$.pipe(throttleTime(100)).subscribe((v) => console.log('throttle', v));
dense$.pipe(auditTime(100)).subscribe((v) => console.log('audit   ', v));
dense$.pipe(delay(100)).subscribe((v) => console.log('delay   ', v));

// Observed output:
//   debounce: 9            <- never fires; 9 flushes on completion
//   throttle: 0, 3, 6, 9   <- first value of each 100ms window
//   audit:    2, 5, 8, 9   <- last value of each 100ms window
//   delay:    0..9         <- all ten values, shifted by 100ms

// ============================================
// PART 10: THE ASSEMBLED PIPELINE
// ============================================
const query$ = fromEvent(searchEl, 'input').pipe(
  map(() => searchEl.value.trim()),
  debounceTime(300),
  distinctUntilChanged()
);

const page$ = fromEvent(window, 'scroll', { passive: true }).pipe(
  throttleTime(100, undefined, { leading: true, trailing: true }),
  map(() => window.scrollY),
  distinctUntilChanged()
);

const cursor$ = fromEvent<MouseEvent>(document, 'mousemove').pipe(
  auditTime(50),
  map((e) => `${e.clientX},${e.clientY}`)
);

merge(
  query$.pipe(map((t) => ({ type: 'query' as const, t }))),
  page$.pipe(map((y) => ({ type: 'scroll' as const, y }))),
  cursor$.pipe(map((p) => ({ type: 'cursor' as const, p })))
).subscribe(handleEvent);

The ten parts built a search box with debounceTime, two scroll handlers with the two throttleTime configs, a cursor trail with auditTime, a gauge with sampleTime, a delayed notice with delay, a staggered entrance with delayWhen, a side-by-side comparison that shows all four operators running on the same source, and finally a merged pipeline that combines three of them.


Quick Reference

The Four Operators

OperatorEdgeValue keptLossy
debounceTime(d)trailinglast of a burstyes
throttleTime(d)leadingfirst of a windowyes
auditTime(d)trailinglast of a windowyes
delay(d)noneall, shifted by dno

The ThrottleConfig Matrix

ConfigBehaviour
{ leading: true, trailing: false }default; first value of each window
{ leading: true, trailing: true }first and last value of each window
{ leading: false, trailing: true }identical to auditTime(d)
{ leading: false, trailing: false }never emits

Notification Behaviour

NotificationdebounceTimethrottleTimedelay
nextpending, after silenceper windowqueued, then replayed
errorpending droppedforwarded at onceforwarded at once
completepending flushedpending trailing flushedafter the queue drains

Related Operators

OperatorUse
debounce(fn)variable quiet period, per value
throttle(fn, cfg)variable window, keeps the config
audit(fn)variable window, trailing edge
sample(fn)external notifier instead of a clock
sampleTime(n)fixed clock, independent of the source
delayWhen(fn, start)per-value delay plus delayed subscription

Best Practices

โœ… Do This:

// Debounce the search box, then dedupe the settled terms
input$.pipe(debounceTime(300), distinctUntilChanged());            // โœ…

// Ask for the trailing value on scroll so the last frame renders
scroll$.pipe(throttleTime(100, undefined, { trailing: true }));    // โœ…

// Use auditTime for pointer position; the trailing edge is the point
move$.pipe(auditTime(50));                                         // โœ…

// Keep delay for notifications you must not lose
notices$.pipe(delay(400));                                         // โœ…

// Turn on passive mode for scroll and touch listeners
fromEvent(window, 'scroll', { passive: true });                    // โœ…

// Cancel in-flight debounced work when a new term settles
term$.pipe(debounceTime(300), switchMap(load));                    // โœ…

// Use sampleTime when the output rate must be fixed
sensor$.pipe(sampleTime(1000), map(toReading));                    // โœ…

โŒ Don’t Do This:

// Debounce a stream that never goes quiet
scroll$.pipe(debounceTime(200));                                   // โŒ

// Dedupe before debounce; the dropped value never restarts the timer
input$.pipe(distinctUntilChanged(), debounceTime(300));            // โŒ

// Run a high-frequency stream through a buffering operator
mousemove$.pipe(delay(1000));                                      // โŒ

// Expect delay to suppress or merge values
clicks$.pipe(delay(0));                                            // โŒ

// Use throttleTime for "when the user stops typing"
input$.pipe(throttleTime(300));                                    // โŒ

// Use debounceTime(0) as a cheap delay; it collapses the burst
of(1, 2, 3).pipe(debounceTime(0));                                 // โŒ

// Leave the subscription open across route changes
term$.pipe(debounceTime(300)).subscribe(search);                   // โŒ

Common Pitfalls

PitfallWhy It HappensFix
One request per keystrokethrottleTime used for a settle-detection jobswap to debounceTime
Search never firesdebounceTime on a stream with no silenceuse auditTime or throttleTime
Page rests one frame shorttrailing: false drops the window’s final valueset trailing: true
Duplicate requestsdistinctUntilChanged placed before debounceTimemove it after
Memory growth on long streamsdelay buffers every pending valueuse a lossy operator instead
Last sample lostsampleTime never flushes on completionadd take or use auditTime
Banner shows a stale errordelay queues values but errors skip the queueclear state on the error path
Handler acts on an old positionthrottleTime leading emits the window’s oldest valueuse auditTime for freshest

Real-World Examples

1. Type-ahead search

term$.pipe(debounceTime(300), distinctUntilChanged(), switchMap(search));

2. Infinite-scroll trigger

scroll$.pipe(
  throttleTime(200),
  filter(() => isNearBottom()),
  map(() => loadNextPage())
);

3. Drag preview at frame rate

pointer$.pipe(
  auditTime(16),                  // one update per 60 Hz frame
  map((e) => ({ x: e.clientX, y: e.clientY }))
);

4. Chart series from a sensor

sensor$.pipe(sampleTime(1000), map(toReading));

5. Sticky header state

scroll$.pipe(
  throttleTime(100, undefined, { trailing: true }),
  map(() => window.scrollY > 80),
  distinctUntilChanged()
);

6. Draft auto-save

editor$.pipe(debounceTime(1500), switchMap(saveDraft));

7. Self-dismissing banner

notice$.pipe(delay(500), takeUntil(dismiss$));

8. Staggered list entrance

from(cards).pipe(delayWhen((card, i) => timer(i * 120)));

9. Debounced window resize

resize$.pipe(debounceTime(200), map(readViewport));

10. Refresh button cooldown

refresh$.pipe(throttleTime(2000), switchMap(poll));

Visual

The debounceTime Timeline

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ debounceTime(300) -> emits the LAST value after silenceโ”‚
โ”‚                                                        โ”‚
โ”‚ source  a  b  c  d              e  f                   โ”‚
โ”‚         |  |  |  |              |  |                   โ”‚
โ”‚ reset   R  R  R  R              R  R                   โ”‚
โ”‚                   +---300ms--+     +---300ms--+        โ”‚
โ”‚ emit                           d             f         โ”‚
โ”‚                                                        โ”‚
โ”‚ the timer restarts on every value, so a source that    โ”‚
โ”‚ never pauses for 300ms produces no output at all       โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

throttleTime โ€” Leading Against Trailing

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ throttleTime(100) - one window, two possible edges     โ”‚
โ”‚                                                        โ”‚
โ”‚ source   a  b  c  d  e  f  g  h  i  j                  โ”‚
โ”‚          |  |  |  |  |  |  |  |  |  |                  โ”‚
โ”‚ windows  [--------]  [--------]  [--]                  โ”‚
โ”‚ leading     a           e           i                  โ”‚
โ”‚ trailing       d           h           j               โ”‚
โ”‚                                                        โ”‚
โ”‚ leading:true is the default; add trailing:true to also โ”‚
โ”‚ deliver the last value of each window                  โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

debounceTime Against auditTime

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ debounceTime vs auditTime on the same dense source     โ”‚
โ”‚                                                        โ”‚
โ”‚ source    a  b  c  d  e  f  g  h  i  j                 โ”‚
โ”‚                                                        โ”‚
โ”‚ debounce  xxxxxxxxxxxxxxxxxxxxxxxxxxxx                 โ”‚
โ”‚           timer restarted by every value               โ”‚
โ”‚           emits j, and only after the source stops     โ”‚
โ”‚                                                        โ”‚
โ”‚ audit     [--------]  [--------]  [--]                 โ”‚
โ”‚           timer never restarts                         โ”‚
โ”‚           emits d, h, j on a fixed cadence             โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

delay Shifts, debounceTime Collapses

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ delay shifts every value; debounceTime keeps the last  โ”‚
โ”‚                                                        โ”‚
โ”‚ source      a   b   c                                  โ”‚
โ”‚             |   |   |                                  โ”‚
โ”‚                   +--- 50ms ---+                       โ”‚
โ”‚                                                        โ”‚
โ”‚ delay(50)                   a   b   c                  โ”‚
โ”‚             lossless: three values, each 50ms later    โ”‚
โ”‚                                                        โ”‚
โ”‚ debounceTime(50)                            c          โ”‚
โ”‚             lossy: the timer restarts, only c survives โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
debounceTime(d)last value, after d ms of silence
throttleTime(d)first value of each d ms window
auditTime(d)last value of each d ms window
sampleTime(d)last value on a fixed d ms grid
delay(d)every value, shifted by d ms
delayWhen(fn)every value, delay chosen per value
Default throttle config{ leading: true, trailing: false }
auditTime equivalentthrottleTime(d, undefined, { leading: false, trailing: true })
Lossless operatorsdelay and delayWhen only
Errorsnever delayed, always forwarded at once
CompletiondebounceTime flushes the pending value

Key takeaways:

  • debounceTime resets its timer on every value. It emits the last value of a burst, and only after dueTime ms of silence. A stream with no silence never produces output, which makes it the wrong choice for scroll and pointer events.
  • throttleTime anchors its window at the emitted value and never restarts it. The default { leading: true, trailing: false } gives an immediate reaction; adding trailing: true delivers the last value of each window so the final state is never missed.
  • auditTime is the trailing half of throttleTime. It keeps the timer running across incoming values and emits the most recent one at the end, which makes it behaviourally identical to throttleTime(d, undefined, { leading: false, trailing: true }).
  • sampleTime uses an external clock. It ticks on its own period regardless of the source and emits only if a new value arrived since the last tick, which is what makes it suitable for fixed-rate charting.
  • delay shifts without dropping. Every value survives, errors pass through immediately, and completion waits for the queue to drain. It is a time translator, not a rate limiter.
  • Order matters between debounceTime and distinctUntilChanged. Dedupe before debounce and a repeated value never restarts the timer, so the operator fires on a stale schedule.
  • All of these introduce latency. throttleTime(200) costs up to 200 ms, debounceTime(300) costs 300 ms plus the wait for silence. The duration is a UX decision, not a performance-only one.

Remember: Rate limiting in RxJS is a question of which value from a window you want, not a question of how many values to throw away. debounceTime wants the last value of a burst and needs silence to find it; throttleTime wants the first value of a window and needs nothing but a clock; auditTime wants the last value of a window and is the version that keeps ticking under pressure; delay wants every value and gives up memory to keep them. Pick by matching the operator’s window to the stream’s shape โ€” silence-seeking for typed input, clock-driven for continuous motion, and lossless for anything that must arrive.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!