Last active
November 30, 2022 11:18
-
-
Save ktnyt/5935755f79f6472b6b9b383fa88d6efe to your computer and use it in GitHub Desktop.
useThrottle hook like thing in Solid.js
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 { | |
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