javascript / intermediate
Snippet
Asynchronous Derived Stores with Debouncing
Derived stores can be asynchronous. By using the 'set' callback, you can delay updates (debouncing), which is useful for preventing excessive API calls during rapid user input.
snippet.js
1
2
3
4
5
6
7
8
9
import { derived } from 'svelte/store';export const debouncedSearch = derived(searchTerm, ($searchTerm, set) => {const timeout = setTimeout(() => {set($searchTerm);}, 300);return () => clearTimeout(timeout);}, '');
svelte
Breakdown
1
derived(searchTerm, ($searchTerm, set) => { ... }, '');
The third argument is the initial value; the second argument provides a 'set' function for async updates.
2
return () => clearTimeout(timeout);
Return a cleanup function that runs every time the input store changes, cancelling previous timers.