Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 381
Fred Hors Avatar asked Dec 10 '25 23:12

Fred Hors


1 Answers

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));
like image 85
H.B. Avatar answered Dec 13 '25 12:12

H.B.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!