1

I am getting a problem in making a countdown timer which will start on clicking on start button and it will stop onClicking on the stop button. I have made that thing on javascript but when I came to reactJs, I am getting unable. I am providing all the codes. And please check what is the problem.

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

const App = () => {
  const [data, setData] = useState(0);
  let interval;
  return (
    <>
      <div id="Message"> {data} </div>
      <button
        onClick={() => {
          interval = setInterval(() => {
            setData(data + 1);
          }, 1000);
        }}
      >
        Start
      </button>
      <button
        onClick={() => {
          clearInterval(interval);
        }}
      >
        End
      </button>
    </>
  );
};
export default App;
0

2 Answers 2

1

Issues

  1. The timer/interval reference is redeclared each render cycle, so you can never clear it once anything causes the component to rerender.
  2. You've a stale enclosure of the data state value in the interval callback.

Solution

  1. Use a React ref to hold the interval reference.
  2. Use a functional state update to correctly update the data counter.

Code

const App = () => {
  const [data, setData] = useState(0);
  const intervalRef = useRef();

  return (
    <>
      <div id="Message"> {data} </div>
      <button
        onClick={() => {
          intervalRef.current = setInterval(() => {
            setData(c => c + 1);
          }, 1000);
        }}
      >
        Start
      </button>
      <button
        onClick={() => {
          clearInterval(intervalRef.current);
        }}
      >
        End
      </button>
    </>
  );
};

Demo

Edit getting-problem-in-making-a-timer-count-down-code-in-reactjs

Sign up to request clarification or add additional context in comments.

Comments

1

Try this out. Basically using State to keep track of the intervals too.

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

function App() {
  const [data, setData] = useState(0);
  const [intervalInstance, setIntervalInstance] = useState(null);
  return (
    <>
      <div id="Message"> {data} </div>
      <button
        onClick={() => {
          const interval = setInterval(() => {
            setData(prevData => prevData + 1);
          }, 1000);
          setIntervalInstance(interval);
        }}
      >
        Start
      </button>
      <button
        onClick={() => {
          clearInterval(intervalInstance);
        }}
      >
        End
      </button>
    </>
  );
}
export default App;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.