Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript React Components (2018) Stateful Components and Lifecycle Methods Resetting the Stopwatch

Alena Miadzvedskaya
Alena Miadzvedskaya
6,386 Points

Can't stop the timer, it still ticks even after stop button was clicked

const Stopwatch = () => { const [isRunning, setIsRunning] = useState(false); const [elapsedTime, setElapsedTime] = useState(0); const [prevTime, setPrevTime] = useState(0);

const intervalID = () => { setInterval(() => tick(), 1000)}

const stopTimer = () => { clearInterval(intervalID) }

const handleStopwatch = () => { setIsRunning(!isRunning); if (!isRunning) { setPrevTime(Date.now()); } };

useEffect(() => { if(isRunning) { intervalID() } else { stopTimer() } }, [isRunning]);

const tick = () => { if (isRunning === true) { const now = Date.now(); const elapsedTimeNow = elapsedTime; const prevTimeNow = prevTime; setPrevTime(now); setElapsedTime(elapsedTimeNow + (now - prevTimeNow)); } };

const seconds = Math.floor(elapsedTime / 1000)

return ( <div className="stopwatch"> <h2>Stopwatch</h2> <span className="stopwatch-time">{ seconds }</span> <button onClick={handleStopwatch}>{isRunning ? "Stop" : "Start"}</button> <button>Reset</button> </div> ); };