I tried with:
let searchText = $derived(debounce((typedText) => typedText, 2000)(typedText));
But searchText is not assigned!
Reproduction with $derived: searchText is not assigned.
Reproduction with $effect(): searchText assignment is not debounced at all.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With