Chalarangelo / 30-seconds-of-react

Short React code snippets for all your development needs
https://www.30secondsofcode.org/react/p/1
Creative Commons Attribution 4.0 International
5.08k stars 485 forks source link

Use an extra param with `useInterval` hook to stop JS Interval based on condition #119

Closed Showrin closed 3 years ago

Showrin commented 3 years ago

Background

I was doing some tweaks with the setInterval function in React. Then, I found the useInterval hook here. The problem I've faced with this hook is I can't stop the interval without unmounting the component. I wanted to stop the interval after a certain time. But I found no options here. Or did I miss something?

Screenshot 2021-05-19 at 10 09 13 AM

Solution

We can add an extra param with useInterval hook that will stop the interval when it's true. Like the following example:

useInterval(
    () => {
      setProgress(progress + 1);
      setTime(time + intervalDelay);
    },
    intervalDelay,
    progress >= initialyCompleted // This is the third param for clearing Interval manually
);

If this issue is valid, then could you please assign this issue to me? I have a working solution and I want to contribute here. Thanks so much.