Search code examples
sveltedebouncingsvelte-5

Is there a way to debounce a Svelte 5 $derived value?


I tried with:

let searchText = $derived(debounce((typedText) => typedText, 2000)(typedText));

But searchText is not assigned!

  1. Reproduction with $derived: searchText is not assigned.

  2. Reproduction with $effect(): searchText assignment is not debounced at all.


Solution

  • A debounce function must only be called once, otherwise one gets new instances with independent timeouts.

    Using an $effect:

    const update = debounce(v => searchText = v, 300);
    $effect(() => update(typedText));
    

    The logic could be wrapped to be compatible with $derived.by:

    function debouncer(getter, wait, immediate) {
        let current = $state();
        const update = debounce(v => current = v, wait, immediate);
        $effect(() => update(getter()));
    
        return () => current;
    }
    
    let typedText = $state();
    const searchText = $derived.by(debouncer(() => typedText, 300));