Skip to content

Instantly share code, notes, and snippets.

@ktnyt
Last active November 30, 2022 11:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ktnyt/5935755f79f6472b6b9b383fa88d6efe to your computer and use it in GitHub Desktop.
Save ktnyt/5935755f79f6472b6b9b383fa88d6efe to your computer and use it in GitHub Desktop.
useThrottle hook like thing in Solid.js
import {
Accessor,
createEffect,
createSignal,
onCleanup,
untrack,
} from 'solid-js'
export const useThrottle = <T>(
source: Accessor<T>,
wait: number | Accessor<number>,
): Accessor<T> => {
const timeout = () => (typeof wait === 'function' ? wait() : wait)
const [signal, setSignal] = createSignal(source())
const init = setInterval(() => setSignal(() => source()), timeout())
const [handle, setHandle] = createSignal(init)
createEffect(() => {
clearInterval(untrack(handle))
setHandle(setInterval(() => setSignal(() => source()), timeout()))
})
onCleanup(() => clearInterval(handle()))
return signal
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment