Skip to content

Instantly share code, notes, and snippets.

@ViliamKopecky
Created March 23, 2022 15:40
Show Gist options
  • Save ViliamKopecky/ece7bcdf61eb8b77bf0150a9569616af to your computer and use it in GitHub Desktop.
Save ViliamKopecky/ece7bcdf61eb8b77bf0150a9569616af to your computer and use it in GitHub Desktop.
useSwitchingInterval
function useSwitchingInterval<Item>(items: readonly Item[], seconds = 2) {
const [active, setActive] = useState(0)
useEffect(() => {
let timeout: null | NodeJS.Timeout = null
const next = () => {
setActive((a) => a + 1)
timeout = setTimeout(next, seconds * 1000)
}
next()
return () => {
if (timeout) {
clearTimeout(timeout)
}
}
}, [seconds])
return items[active % items.length]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment