0

I am trying to build a timer, and I use an interval to build it. For some reason though, instead of deducting just .1 form the number ever 100 milliseconds, it starts off by doing so and then get weird.

I've printed what the new values is, and this is what I get. Why Is that?

time left 9.8
index.js:18 time left 9.700000000000001
index.js:18 time left 9.600000000000001
index.js:18 time left 9.500000000000002
index.js:18 time left 9.400000000000002
index.js:18 time left 9.300000000000002
index.js:18 time left 9.200000000000003
index.js:18 time left 9.100000000000003
index.js:18 time left 9.000000000000004
index.js:18 time left 8.900000000000004
index.js:18 time left 8.800000000000004
index.js:18 time left 8.700000000000005

My code:

  const [timeLeft, setTimeLeft] = useState(10);
  let interval = useRef(null);

  useEffect(() => {
    interval.current = setInterval(() => {
      setTimeLeft((tl) => tl - 0.1);
    }, 100);
    return () => clearInterval(interval.current);
  }, []);

  useEffect(() => {
    console.log("time left", timeLeft);
    if (timeLeft === 0) clearInterval(interval.current);
  }, [interval, timeLeft]);

I've tried using toFixed but I still can't make it stop on 0:

  useEffect(() => {
    if (timeLeft.toFixed(0) === 0) {
      console.log("clearing time left", timeLeft.toFixed(0));
      clearInterval(interval.current);
    } else {
      console.log("notclearing time left", timeLeft.toFixed(0));
    }
  }, [interval, timeLeft]);

This is part of the new log. It prints 0, so why doesn't it stop?

10index.js:20 notclearing time left 2
10index.js:20 notclearing time left 1
5index.js:20 notclearing time left 0
5index.js:20 notclearing time left -0
10index.js:20 notclearing time left -1
Tsabary
  • 3,119
  • 2
  • 24
  • 66

0 Answers0