Skip to content

When using useInterval is there a way to stop after a certain amount of time? #4

Answered by hazae41
wontondon asked this question in Q&A
Discussion options

You must be logged in to vote

You can achieve this by using a variable

export function useInterval<K, D, F>(query: Query<K, D, F>, interval: number, active: boolean) {
  const { ready, fetch } = query

  useEffect(() => {
    if (!ready)
      return
    if (!interval)
      return
    if (!active)
      return

    const f = () => fetch().then(r => r.ignore())
    const i = setInterval(f, interval)
    return () => clearInterval(i)
  }, [ready, fetch, interval, active])
}

Or by simply setting the interval value to 0

Put the variable in a useState, and then use the abort event of the AbortSignal to do setState(false)

const aborter = useRef(new AbortController())
const [interval, setInterval] = useState(1000)

useEffect((

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@wontondon
Comment options

Answer selected by wontondon
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants