@sv-use/core
Version:
A collection of Svelte 5 utilities.
35 lines (34 loc) • 1.08 kB
JavaScript
/**
* A reactive state that updates its value after a delay.
* @param initial The initial value of the state.
* @param options Additional options to customize the behavior.
* @see https://svelte-librarian.github.io/sv-use/docs/core/debounced-state
*/
export function debouncedState(initial, options = {}) {
const { delay = 1000 } = options;
let timeout;
const _state = $state({ current: initial });
const handler = {
get(target, key) {
if (target &&
typeof target === 'object' &&
typeof target[key] === 'object' &&
target[key] !== null) {
return new Proxy(target[key], handler);
}
else {
return target[key];
}
},
set(target, key, value) {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(() => {
target[key] = value;
}, delay);
return true;
}
};
return new Proxy(_state, handler);
}