简体   繁体   中英

Why my variable "intervalId" is not getting the value updated when I call the function "StopTimer" function?

Here is my simple code:

import React, { useState } from "react";
import "./App.css";

function App() {
  const [time, setTime] = useState(0);
  var intervalId;

  function startTimer() {
    intervalId = setInterval(() => {
      setTime(time => time + 1);
    }, 1000);
    console.log("My interval id is: ", intervalId);
  }

  function stopTimer() {
    console.log("Clearing intervalId", intervalId);
    clearInterval(intervalId);
  }

  return (
    <div className="App">
      <div>{time}</div>
      <div>
        <button onClick={startTimer}>Start time</button>
        <button onClick={stopTimer}>Stop time</button>
      </div>
    </div>
  );
}

Here is the representation of the error

I press Start Time button and then the Stop Time Button , but my variable intervalId in the stopTimer function is not getting the updated value from the setInterval function. Why?.

Because intervalId is not the same variable that was in scope when startTimer was invoked. It will be undefined in all the subsequent renders. ( caused when time change state )

In React, if you want to "keep a value" across the life cycle of a component, you can use a ref for it:

  // ....
  var intervalId = React.useRef();
  // ....
  intervalId.current = setInterval(() => {
  // ...
  clearInterval(intervalId.current);

Since the App is invoked everytime you change the state ( setTime ), you get a new, fresh value of the local variable.

One of options is to include the variable in your state.

function App() {
  var [time, setTime] = useState(0);
  var [intervalId, setIntervalId] = useState(0);

  function startTimer() {
    setIntervalId(intervalId => setInterval(() => {
      setTime(time => time + 1);
    }, 1000));
  }

  function stopTimer() {
    clearInterval(intervalId);
  }

  return (
    <div className="App">
      <div>{time}</div>
      <div>
        <button onClick={startTimer}>Start time</button>
        <button onClick={stopTimer}>Stop time</button>
      </div>
    </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