Skip to content

Instantly share code, notes, and snippets.

@crazy4groovy
Last active November 21, 2024 15:03
Show Gist options
  • Save crazy4groovy/46126903982cae45117e9f7c5f0f9dd8 to your computer and use it in GitHub Desktop.
Save crazy4groovy/46126903982cae45117e9f7c5f0f9dd8 to your computer and use it in GitHub Desktop.
debounced Svelte store (JavaScript)
<script lang="ts">
/// ...
import { customStoreDebouncer /*, storeDebouncer */ } from "./stores/stringStore";
const stringStoreDebounced = customStoreDebouncer(400); // debounced store read
$: {
const text = $stringStoreDebounced; // resolved value, after debounce timeout
/// ...
}
</script>
{#if $stringStoreDebounced.length < 3}
<button on:click={() => alert(1)} title="Prev Page">⏮</button>
{/if}
<script lang="ts">
import { store } from "../stores/searchText";
export let placeholder = "";
function handleInput(target) {
store.set(target.value); // normal store write
}
</script>
<input
type="text"
on:input={(e) => handleInput(e.target)}
class:inactive={$store.length <= 2}
{placeholder}
/>
import { get, derived, type Writable } from "svelte/store";
export const debouncer = <T>(store: Writable<T>, timeoutMs = 500) =>
derived(
store,
($value, set) => {
const intervalId = setTimeout(() => set($value), timeoutMs);
return () => clearTimeout(intervalId);
},
get(store)
);
import { writable } from "svelte/store";
import { debouncer } from "./debouncer";
export const store = writable<string>("");
export const storeDebouncer = debouncer(store); // default debounce timeout
export const customStoreDebouncer = (timeoutMs?: number) => debouncer(store, timeoutMs); // custom debounce timeout
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment