@sv-use/core
Version:
A collection of Svelte 5 utilities.
28 lines (27 loc) • 776 B
JavaScript
import { untrack } from 'svelte';
/**
* Debounces the update of the value after a delay.
* @param initial The reactive value as a getter.
* @param options Additional options to customize the behavior.
* @see https://svelte-librarian.github.io/sv-use/docs/core/debounce
*/
export function debounce(value, options = {}) {
const { delay = 1000 } = options;
let timeout;
const _state = $state({ current: undefined });
$effect(() => {
value();
if (timeout) {
clearTimeout(timeout);
}
untrack(() => {
timeout = setTimeout(() => {
_state.current = value();
}, delay);
});
return () => {
clearTimeout(timeout);
};
});
return _state;
}