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

Function debounced

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

Source from the content-addressed store, hash-verified

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

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