clearInterval Handler not working?

Hello! I am working on the 25 + 5 Clock and want to create a handler to start the clock countdown and then another to stop the countdown and reset it. I cannot seem to make clearInterval work outside of the function. I am assuming it has to do with scope maybe? My brain is melting trying to think about this and it is taking up too much time (spent several hours googling today for a solution) and was hoping someone would have some insight. I am sure I am just missing something but a little help pointing me in the right direction would be greatly appreciated. Thanks!

  var interval;

  const startHandler = () => {
    interval = setInterval(
      () => setSessionTimerLength((previousTime) => previousTime - 1),

  const resetHandler = () => {

That looks roughly right to me, based on the little that you’re showing. There may be a larger issue. You mention scope - it is hard to tell without seeing all the code. It may be that that variable interval is getting overwritten at some point. Again, we’d need to see the code.

If you built this in an online IDE, do you have a link to that? If you built it locally, can you give a link to a repo?

1 Like

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).


Thank you for your reply! Let me just provide a link below on CodePen.

Moving the interval declaration out of the component should work. But I’m not sure how you plan to handle pausing? Right now it would just fire the setInterval again.

I might also look into using useEffect for the timer. If you search for React timer you should get some example code.

Hey, that worked! Could you explain why that worked? And also, I don’t have a plan for pause yet… haha. I see what you mean though, that is an obstacle.

My guess would be that because it is in the component, it gets redeclared on each render. Another option I assume would be to make it a state hook.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.