MCPcopy Create free account
hub / github.com/angular/angular / debounced

Function debounced

packages/core/src/resource/debounce.ts:36–165  ·  view source on GitHub ↗
(
  source: () => T,
  wait: NoInfer<DebounceTimer<T>>,
  options?: NoInfer<DebouncedOptions<T>>,
)

Source from the content-addressed store, hash-verified

34 * @see [Debouncing signals with `debounced`](guide/signals/debounced)
35 */
36export function debounced<T>(
37 source: () => T,
38 wait: NoInfer<DebounceTimer<T>>,
39 options?: NoInfer<DebouncedOptions<T>>,
40): Resource<T> {
41 if (isInParamsFunction()) {
42 throw invalidResourceCreationInParams();
43 }
44 if (ngDevMode && !options?.injector) {
45 assertInInjectionContext(debounced);
46 }
47 const injector = options?.injector ?? inject(Injector);
48
49 let active: Promise<void> | void | undefined;
50 let pendingValue: T | undefined;
51 let activeTimer: ReturnType<typeof setTimeout> | undefined;
52
53 const cancelTimer = () => {
54 if (activeTimer !== undefined) {
55 clearTimeout(activeTimer);
56 activeTimer = undefined;
57 }
58 };
59
60 injector.get(DestroyRef).onDestroy(() => {
61 cancelTimer();
62 active = undefined;
63 });
64
65 const state = linkedSignal<
66 {value: T; thrown: false} | {error: unknown; thrown: true},
67 ResourceSnapshot<T>
68 >({
69 source: () => {
70 try {
71 setInParamsFunction(true);
72 return {value: source(), thrown: false};
73 } catch (err) {
74 rethrowFatalErrors(err);
75 return {error: err, thrown: true};
76 } finally {
77 setInParamsFunction(false);
78 }
79 },
80 computation: (res, previous) => {
81 // If we already have a state from the effect or a previous read, keep it!
82 // The effect is responsible for timing and state transitions.
83 if (previous !== undefined) {
84 return previous.value;
85 }
86
87 // On the very first evaluation, determine the initial state synchronously.
88 if (res.thrown) {
89 return {status: 'error', error: res.error as Error};
90 }
91 return {status: 'resolved', value: res.value};
92 },
93 });

Callers 5

debounce_spec.tsFile · 0.90
DebounceBugClass · 0.90
validateAsyncFunction · 0.90
SearchClass · 0.90
debounce.spec.tsFile · 0.85

Calls 15

isInParamsFunctionFunction · 0.90
assertInInjectionContextFunction · 0.90
injectFunction · 0.90
linkedSignalFunction · 0.90
setInParamsFunctionFunction · 0.90
rethrowFatalErrorsFunction · 0.90
effectFunction · 0.90
untrackedFunction · 0.90
resourceFromSnapshotsFunction · 0.90
cancelTimerFunction · 0.85
sourceFunction · 0.85

Tested by

no test coverage detected