WeCodeAcademy

Step 5: A countdown timer with useEffect

Add pressure: 10 seconds per question. A timer is a side effect, so it lives in useEffect. The effect starts a setInterval, and returns a cleanup function that stops it: without that, old timers would pile up each time the question changes. The resetKey makes the effect restart for each new question, and a second effect calls onExpire when the time runs out, which counts as a wrong answer.

Examplereact
Open in editor »

Wait without answering and watch the question lock when the time reaches zero. Try removing the return () => clearInterval(id) line to see the countdown speed up as intervals stack: that bug is why cleanup functions exist.

Your turn: write the code

Write formatTime(seconds) that returns minutes and seconds as m:ss, so formatTime(75) is 1:15 and formatTime(5) is 0:05. Print formatTime(75), formatTime(5) and formatTime(600).

Quick check

What does the function returned from useEffect do?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.