25+5 clock react useEffect/setInterval bug

Hi,
I have finished writing the functional part of the code. It seems that I am using useEffect, useState and setInterval together in a wrong way. The problem: my clock starts with a 2 second interval. After that it continues with the intended 1 sec interval. Same thing happens when I pause/start my clock. So it happens when I set the endTime to base my calculation of remaining time.
Here is the link for working code https://codesandbox.io/s/jovial-cloud-9nd46?file=/clock.js

Any advice on where my logic got derailed is appreciated. Also any other advice on how to make the code more clean “react” :slight_smile:

The only place that clearInterval is called is in the function returned by useEffect. This function will not be called until the component unmounts. You need to call clearInterval explicitly whenever the timer is stopped.

Thanks for the feedback.
I am changing state whenever timer is stopped. So this would cause the component to unmount and also to clearInterval. If I set and clearInterval outside useEffect it wont persist its value through re-rendering. Could you give me an exmple how to explicitly call clearInterval so that it works?!

1 Like

I’ve read it twice now. Most forum threads on different platforms end up with this link sooner or later. So is there no way of solving this without creating custom hook? Or is custom hook just more efficient for this interval problem?!

I’m not sure if this solves your problem, I ran into a similar issue and I haven’t solved it yet but I think this video gave me what I need to solve it. Wanted to post this here before I forgot https://www.youtube.com/watch?v=sWKz9aLovjY&t=3167s

1 Like

Thanks for the link. I found the explanation about useEffect very clear and easy to grasp for a like beginner like myself. I ended up rewriting my code without comparing actual system time. Instead I deduct seconds. So I didn’t actually solve the issue but my timer now passes all the tests :slight_smile:

1 Like

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