A
A
Alexander Osadchy2020-11-23 10:42:45
React
Alexander Osadchy, 2020-11-23 10:42:45

How to start a timer in react when a button is clicked?

Hello!

Can you please tell me how to start the timer after clicking on the button?

That is, I have a button:

<Button disabled={isSubmitting || nextButton} htmlType="submit" type="primary">
          Submit
        </Button>


After clicking on which the timer start function should work:
const [seconds, setSeconds] = useState(60);

    useEffect(() => {
        if (seconds > 0) {
          setTimeout(() => setSeconds(seconds - 1), 1000);
          toggleNextButton(true);
        } else {
          toggleNextButton(false);
        }
    });


Timer output: The
{seconds}

question is, how to start the timer when clicked?..and hide the counter when the timer expires?

--------------------

Tried like this:
5fbb6973a8840868574222.bin

<Button disabled={isSubmitting || nextButton} onClick={handleClick} htmlType="submit" type="primary">
          Submit
        </Button>


But..it doesn't work

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-11-23
@DELUX

function App() {
  const [ seconds, setSeconds ] = React.useState(60);
  const [ timerActive, setTimerActive ] = React.useState(false);

  React.useEffect(() => {
    if (seconds > 0 && timerActive) {
      setTimeout(setSeconds, 100, seconds - 1);
    } else {
      setTimerActive(false);
    }
  }, [ seconds, timerActive ]);

  return (
    <div>
      {seconds
        ? <React.Fragment>
            <button onClick={() => setTimerActive(!timerActive)}>
              {timerActive ? 'stop' : 'start'}
            </button>
            <div>{seconds}</div>
          </React.Fragment>
        : <button onClick={() => setSeconds(60)}>ещё раз</button>
      }
    </div>
  );
}

https://jsfiddle.net/9rx1qhsy/1/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question