Last active
November 21, 2024 15:03
-
-
Save crazy4groovy/46126903982cae45117e9f7c5f0f9dd8 to your computer and use it in GitHub Desktop.
debounced Svelte store (JavaScript)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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} | |
/> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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