Start learning free

LESSON 129 OF 161 · FRONTEND: FRONTEND WITH AI

A Countdown Stuck at 9 in JavaScript

Practice

An AI assistant wrote the flash-sale countdown for the Corner Shop. It looks right, but when a visitor opens the page, it goes from 10 to 9 and stays at 9. Here is the AI's effect:

useEffect(() => {
  setInterval(() => {
    setSeconds(seconds - 1);
  }, 1000);
}, []);

With [], the effect runs once, on the first draw, when seconds is 10. The interval's function was made in that draw, so it always sees that 10: a stale closure. Every tick sets 10 - 1, and the screen shows 9 forever.

The fix has two parts. First, give the setter an updater: a function React calls with the latest value, like setStock((n) => n - 1) for a stock counter. Second, return a cleanup from the effect that stops the interval with clearInterval. main.jsx uses StrictMode, which runs each effect twice in development: without a cleanup, two intervals tick and the countdown drops by 2 each second.

The check opens the page and lets 3 seconds pass:

> open the page   →  text: The sale ends in 10 seconds
> 1000 ms pass    →  text: The sale ends in 9 seconds
> 2000 ms pass    →  text: The sale ends in 7 seconds

Your task: in src/Countdown.jsx, the AI's effect is empty now. Start an interval that counts down with the updater form, and clear it in the effect's cleanup.


Assignment
Follow the Coding Tutorial to rebuild the countdown's effect: an interval that subtracts 1 from the latest value every second, and a cleanup that clears it.


Hint
Keep the id setInterval returns in timer, and pass it to clearInterval in the cleanup. The updater takes current and returns current - 1.


STEP 1 OF 4
    Ctrl + Enter to check

    Aiui Stale Closure in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free