Spoosh
Plugins

Debounce

Delay requests until input stops changing

The debounce plugin delays requests until the user stops typing or changing input. This prevents excessive API calls during rapid input.

Installation

npm install @spoosh/plugin-debounce

Usage

import { Spoosh } from "@spoosh/core";
import { debouncePlugin } from "@spoosh/plugin-debounce";

const client = new Spoosh<ApiSchema, Error>("/api").use([debouncePlugin()]);

// Wait 300ms after typing stops before fetching
results = injectRead(
  (api) => api("search").GET({ query: { q: searchTerm() } }),
  { debounce: 300 }
);

Conditional Debounce

Only debounce when specific fields change:

results = injectRead(
  (api) => api("search").GET({ query: { q: searchTerm(), page: page() } }),
  {
    debounce: ({ prevQuery }) => (prevQuery?.q !== searchTerm() ? 300 : 0),
  }
);

In this example, debounce is applied when the search query changes, but not when only the page changes.

Options

Per-Request Options

OptionTypeDescription
debouncenumber | (context) => numberMilliseconds to wait, or function for conditional debounce

Debounce Function Context

When using a function, you receive:

PropertyTypeDescription
prevQueryobjectPrevious query parameters
prevParamsobjectPrevious path parameters

Example: Search Input

@Component({
  selector: "app-search-page",
  template: `
    <div>
      <input
        [ngModel]="searchTerm()"
        (ngModelChange)="searchTerm.set($event)"
        placeholder="Search..."
      />
      @if (results.loading()) {
        <app-spinner />
      }
      @for (result of results.data(); track result.id) {
        <app-search-result [result]="result" />
      }
    </div>
  `,
})
export class SearchPageComponent {
  searchTerm = signal("");

  results = injectRead(
    (api) => api("search").GET({ query: { q: this.searchTerm() } }),
    {
      enabled: this.searchTerm().length > 0,
      debounce: 300,
    }
  );
}

On this page