Direct 96
Direct 96

Reputation: 137

Why my clearInterval in React doesn't work?

when I click to to change code I see inly consols.log. I try to understand it but I can't find the answer..

function App() {
  const [laps, setLaps] = useState(0);
  const [running, setRunning] = useState(false);
  const startTime = Date.now() - laps;

   useEffect(() => {
    function interval() {
      setInterval(() => {
        setLaps(Date.now() - startTime);
      }, 100);
    }

    if (!running) {
      clearInterval(interval);
      console.log('ok');
    } else {
      interval();
      console.log('no');
    }
    console.log(running);
  }, [running]);

  return (
    <div className="App">
        <label>Count: {laps}</label>
        <button onClick={() => setRunning(!running)}>{running ? 'stop' : 'start'}</button>
        <button>Clear</button>
    </div>
  );
}

In clean JavaScript this code should works correctly(of course without JSX)?

Upvotes: 1

Views: 2314

Answers (1)

Tholle
Tholle

Reputation: 112787

clearInterval expects a number as argument that is returned from setInterval, but you are giving it the interval function as argument.

You could instead just create the interval if running is true, and return a cleanup function from useEffect that will be run the next time the effect is run.

const { useState, useEffect } = React;

function App() {
  const [laps, setLaps] = useState(0);
  const [running, setRunning] = useState(false);
  const startTime = Date.now() - laps;

  useEffect(
    () => {
      if (running) {
        const interval = setInterval(() => {
          setLaps(Date.now() - startTime);
        }, 100);
        return () => clearInterval(interval);
      }
    },
    [running]
  );

  return (
    <div className="App">
      <label>Count: {laps}</label>
      <button onClick={() => setRunning(!running)}>
        {running ? "stop" : "start"}
      </button>
      <button>Clear</button>
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div>

Upvotes: 3

Related Questions