A countdown needs a clock: something that runs your code once a second. In the browser that is setInterval(fn, 1000), which calls fn every 1000 ms until you pass its id to clearInterval. In React, you start it in a useEffect and clear it in the effect's cleanup, the function the effect returns. React runs the cleanup before the effect runs again and when the component goes away.
For example, a counter that goes up once a second for as long as it is on the page:
const [ticks, setTicks] = useState(0);
useEffect(() => {
const id = setInterval(() => setTicks((t) => t + 1), 1000);
return () => clearInterval(id);
}, []);
The updater (t) => t + 1 matters: the interval's function is made once, so it asks React for the newest value instead of using the one it saw when it was made. The starting code has the Minutes and Seconds fields, format, the left and running states, and the Start and Reset buttons.
The check runs on a fake clock, and your page must answer:
> type "5" into "Seconds" → Time left: 1:05 > click "Start" → no change > 1000 ms pass → Time left: 1:04 > 5000 ms pass → Time left: 0:59 > click "Pause" → no change > 3000 ms pass → no change > click "Start" → no change > 58000 ms pass → Time left: 0:01 > 1000 ms pass → Time left: 0:00, alert: Time is up > 2000 ms pass → no change > click "Reset" → Time left: 1:05, the alert is gone
Your task: finish start, write an effect that runs one interval while running is true and clears it in its cleanup, add a Pause button, stop the timer at 0, and show Time is up.
Assignment
Follow the Coding Tutorial to make the timer count down once a second, pause, stop at zero and say that time is up.
Hint
Start may set left only when it is null or 0, or a Pause would act as a restart. If the time drops two seconds at a time, an old interval was never cleared.
Free plan: 30 tutor messages. PRO is unlimited.
