简体   繁体   中英

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)?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM