← Back to Angular, page 5

angular-0100 · Hard senior

Write a reusable debounced signal utility. How do you handle timers, cleanup and the difference between a debounced signal and a debounced observable?

A debounced signal reads a source signal and updates its own value only after the source has been quiet for a set time. Implement it with an effect that starts a timer and uses the cleanup callback to cancel the previous timer, or use toObservable with debounceTime and toSignal. Test with fakeAsync and flush effects with detectChanges or TestBed.tick.

Full answer

Search boxes, filters and autosave need debouncing: wait until the user pauses before doing expensive work. With signals the source is a signal (query), and you want a second signal (debouncedQuery) that follows it after a delay.

Approach 1: effect with cleanup. The effect reads the source, schedules a setTimeout to set the output, and registers a cleanup function that clears the timer. When the source changes before the timer fires, Angular runs the cleanup first (cancelling the old timer), then runs the effect again (starting a new timer). Only the final value reaches the output. Need an injection context (it creates an effect), and an initial value for the first read.

Approach 2: RxJS interop: toSignal(toObservable(source).pipe(debounceTime(300)), { initialValue }). It is short and gives access to all operators (distinctUntilChanged, switchMap). Both functions need an injection context. Note that toObservable also uses an effect, so values pass through change detection first.

Which to choose: the effect version has no RxJS dependency and is very small, but it only debounces. If the next step is an HTTP call, with cancellation, use the RxJS version, or feed the debounced signal into resource or httpResource as a params source, which cancels stale requests for you.

Details that matter:

  • Equality: set the output only when the value is different (signals do this by default for primitives).
  • Cleanup on destroy: effects are destroyed with their injection context, and the cleanup callback also runs then, so the pending timer does not fire on a destroyed component.
  • Writing to a signal: here the write happens in a timer callback, outside the reactive context. Since Angular 19, writing signals inside effects is allowed anyway (the old allowSignalWrites option is no longer needed), but a write inside the effect body can cause extra runs, so prefer computed or linkedSignal for derived values.
  • SSR: a setTimeout on the server delays nothing important, but pending timers can keep the process busy, so avoid long delays on the server.

Test it: use fakeAsync, set the source, call TestBed.tick() to flush the effect, tick(ms) to advance time, and assert the output.

typescript
// file: debounced.ts
import { Injector, Signal, assertInInjectionContext, effect, inject, signal, untracked } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { debounceTime } from 'rxjs';

export function debounced<T>(source: Signal<T>, ms: number, injector?: Injector): Signal<T> {
  if (!injector) {
    assertInInjectionContext(debounced);
  }
  const output = signal(untracked(source));
  effect(
    (onCleanup) => {
      const value = source();
      const timer = setTimeout(() => output.set(value), ms);
      onCleanup(() => clearTimeout(timer));
    },
    { injector: injector ?? inject(Injector) },
  );
  return output.asReadonly();
}

export function debouncedWithRxjs<T>(source: Signal<T>, ms: number): Signal<T> {
  return toSignal(toObservable(source).pipe(debounceTime(ms)), { initialValue: untracked(source) });
}

// file: search-box.component.ts
import { Component, signal } from '@angular/core';
import { debounced } from './debounced';

@Component({
  selector: 'app-search-box',
  template: `
    <input aria-label="Search" [value]="query()" (input)="query.set($any($event.target).value)" />
    <p>Searching for: {{ term() }}</p>
  `,
})
export class SearchBoxComponent {
  readonly query = signal('');
  readonly term = debounced(this.query, 300);
}

// file: debounced.spec.ts
import { fakeAsync, TestBed, tick } from '@angular/core/testing';
import { signal } from '@angular/core';
import { debounced } from './debounced';

describe('debounced', () => {
  it('emits only the last value after the pause', fakeAsync(() => {
    const query = signal('');
    const term = TestBed.runInInjectionContext(() => debounced(query, 300));
    TestBed.tick();

    query.set('a');
    TestBed.tick();
    tick(100);
    query.set('an');
    TestBed.tick();
    tick(100);
    query.set('ang');
    TestBed.tick();

    tick(299);
    expect(term()).toBe('');
    tick(1);
    expect(term()).toBe('ang');
  }));

  it('clears the pending timer when destroyed', fakeAsync(() => {
    const query = signal('');
    const term = TestBed.runInInjectionContext(() => debounced(query, 300));
    TestBed.tick();

    query.set('x');
    TestBed.tick();
    TestBed.resetTestingModule(); // destroys the injector and the effect
    tick(300);

    expect(term()).toBe('');
  }));
});

Angular 20.3, type-checked, and a Karma spec using `fakeAsync` and `TestBed.tick` checks that only the last value is emitted after the pause, and that the timer is cleared when the component is destroyed.

Key points

  • Effect plus `setTimeout` plus cleanup gives a debounced signal. The cleanup cancels the previous timer.
  • `toSignal(toObservable(s).pipe(debounceTime(ms)))` is the RxJS alternative with more operators.
  • Needs an injection context. Feed the result into `resource` for cancellation of stale requests.
  • Test with `fakeAsync`, `TestBed.tick`, and `tick`.

Common mistakes

  • Not cancelling the previous timer, so every keystroke produces an update.
  • Calling the utility outside an injection context.
  • Debouncing and then ignoring cancellation of the HTTP request that follows.

Follow-ups

  • When is writing a signal inside an effect a bad idea, and what would you use instead?
  • How would you add a "leading edge" option?
  • How does `resource` cancel a stale request?

Tips

  • Show both versions and say when you pick each.
  • Explain the cleanup callback order in one sentence.
  • Mention testing with `fakeAsync`.

Evaluation rubric

  • Implements a correct, cleaned-up debounce.
  • Compares with the RxJS approach.
  • Tests time-based behaviour properly.