I'm working on a React component where on form submit, a timer takes in the value input from a slider component and starts to count down to zero. However, it is only the timer stops after 1 of the setInterval function in triggerClock(). I'm not sure what to do.
My React component:
const Home = (props) => { let timeInMinutes; let timeInSeconds; const [time, setTime] = useState(0); const [minutes, setMinutes] = useState(0); const [seconds, setSeconds] = useState(0); const handleTimeChange = (event) => { setTime(event.target.value); }; const triggerClock = () => { const interval = setInterval(() => { if (minutes === 0 && seconds === 0) { clearInterval(interval); } if (seconds === 0) { setSeconds((sec) => sec + 59); setMinutes((min) => min - 1); } else { setSeconds((sec) => sec - 1); } }, 1000); return () => { clearInterval(interval); }; }; const handleFormSubmit = (event) => { event.preventDefault(); timeInMinutes = time; timeInSeconds = timeInMinutes * 60; setMinutes(timeInSeconds / 60); setSeconds(timeInSeconds % 60); triggerClock(); }; return ( <React.Fragment> <Header /> <Container maxWidth="xs" sx={{ textAlign: "center" }}> <Typography variant="h5">Set Time (Minutes)</Typography> <Box component="form" onSubmit={handleFormSubmit}> <Slider aria-label="Timer" valueLabelDisplay="auto" step={10} marks min={0} max={60} value={time} onChange={handleTimeChange} /> <Button type="submit">Submit</Button> </Box> <div> {minutes}:{seconds} </div> </Container> </React.Fragment> ); };