Kanwarjeet Singh
Kanwarjeet Singh

Reputation: 745

start timer when user click button, React native

I created a function in which when user click start button timer will start, but it's not working. Can someone tell me why it's not working? please

that's the function I created

const [time,setTime] = useState(0)

  const timeout = setInterval(() => {
        if (time !== 60) {
          setTime(prevState => prevState + 1);
        }
      }, 1000);
      console.log(timeout);
      return () => {
        if (time == 60) {
          clearTimeout(timeout);
        }
      };```

Upvotes: 0

Views: 1615

Answers (2)

Easteryard
Easteryard

Reputation: 26

To answer your question:

why is my code not working?

Your state timer starts out being 0 and will therefore never reach inside the if statement.

As Matt U pointed out you most likely want to use setInterval since it runs the function you pass at every X milliseconds (1000 in your case) until you stop it.

See the following for more information regarding that:

What yesIamFaded answered should do the job in your use case, though it would be better to make use of updateState's argument prevState (or whatever you want to call it). updateState will receive the previous value and use that to compute a new value.

const [state, updateState] = useState({ timer: 60 })

const interval = setInterval(() => {
    if (state.timer > 0) {
        updateState(prevState => { timer: prevState.timer - 1 });
    }
}, 1000);

You can read more about functional updates here: https://reactjs.org/docs/hooks-reference.html#functional-updates

And lastly, you should clear the timeout and/or interval once you don't need it anymore using either clearTimeout() or clearInterval().

See the following for more information here:

P.S.

If your timer state isn't coupled with any other state I wouldn't put it into an object. Instead I would do the following:

const [timer, setTimer] = useState(60)

const interval = setInterval(() => {
    if (timer > 0) {
        setTimer(prevTimer => prevTimer - 1 );
    }
}, 1000);

That way you won't have an unnecessary object.

Upvotes: 1

yesIamFaded
yesIamFaded

Reputation: 2068

You could declare the Timer State as 60 instead of 0 and

const [state,updateState] = useState({timer:60})

then call this in updateState: ({timer: timer - 1})

Upvotes: 2

Related Questions