Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

javascript - clearinterval is not working in react hooks

I am creating a simple timer, when the user clicks on start timer, the timer start's and when the user clicks on stop timer the timer stops. But clearinterval is not working, i even tried

import React, { useEffect, useState } from "react";
import Container from "react-bootstrap/Container";
import Row from "react-bootstrap/Row";
import Col from "react-bootstrap/Col";
import Button from "react-bootstrap/Button";

const App = () => {
  const [seconds, setSeconds] = useState(0);
  const [minutes, setminutes] = useState(0);
  const [hour, sethour] = useState(0);
  const [start, setStart] = useState(false);

  const handleStartBtn = () => {
    setStart(!start);
    let id;
    if (!start) {
      id = setInterval(() => setSeconds(sec => sec + 1), 1000);
    } else {
      clearInterval(id);
    }
  };

  return (
    <div className="timer">
      <Container>
        <Row>
          <Col>
            <span className="mr-3">hour:-{hour}</span>
            <span className="mr-3">minutes:-{minutes}</span>
            <span className="mr-3">seconds:-{seconds}</span>
          </Col>
        </Row>
        <Row>
          <Button onClick={handleStartBtn}>{!start ? "start" : "stop"}</Button>
        </Row>
      </Container>
    </div>
  );
};

export default App;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The only time clearInterval is ever called, id is undefined. (That is, it's declared as a variable within that function's scope but has no value set to it.) You need to store the value of that id so you can access it later. Since this is a React component, state is a reasonable place to store it. For example:

const [intervalId, setIntervalId] = useState(0);

Then set that state when setting the interval:

setIntervalId(setInterval(() => setSeconds(sec => sec + 1), 1000));

And then when you clear the interval you can use the ID value from state:

clearInterval(intervalId);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...