Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript React Components Stateful Components and Lifecycle Methods Resetting the Stopwatch

Alena Miadzvedskaya
Alena Miadzvedskaya
6,241 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> ); };