DEV Community

Fatima Alam
Fatima Alam

Posted on

Start and Stop Timer

const App = () => {
  const [count, setCount] = React.useState(0);
  const [isCount0, setIsCount0] = 
  React.useState(true);
  const [id, setId] = 
  React.useState(true);


  React.useEffect(() => {
    console.log("Inside useEffect");
    // setIsCount0(false);
    setCount(0);
     const newId = setInterval(() => setCount((prev) => prev + 1), 1000);
    setId(newId);
    console.log("id = ",id)
  }, [isCount0]);


  const clearTimer = () => {
    // console.log("cleartime", id);

    clearInterval(id);
    setCount(0);
  }


  const startTimer = () => {
    if(count!=0)
    {
      console.log("start timer");
      clearInterval(id);
    }
    setIsCount0((prev) => !prev);
  }

  return(
    <div>
      <h3>Count : {count}</h3>
      <button onClick = {clearTimer}>Stop timer</button>
      <button onClick = {startTimer}>Start timer</button>
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById("root"));
Enter fullscreen mode Exit fullscreen mode

Top comments (0)