Answer the question
In order to leave comments, you need to log in
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>
const [seconds, setSeconds] = useState(60);
useEffect(() => {
if (seconds > 0) {
setTimeout(() => setSeconds(seconds - 1), 1000);
toggleNextButton(true);
} else {
toggleNextButton(false);
}
});
{seconds}
<Button disabled={isSubmitting || nextButton} onClick={handleClick} htmlType="submit" type="primary">
Submit
</Button>
Answer the question
In order to leave comments, you need to log in
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>
);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question