Home > other >  React.js, implementing timer, getting weird behaviour
React.js, implementing timer, getting weird behaviour

Time:03-15

I am trying to create a simple timer with React, where start button starts the timer, and stop button pauses it. However this gives some unexpected behavior.

First click on start, the timer changes to 1 and pauses, on second click it oscillates between 1 and 2. Unable to understand why this is happening. Any help would be greatly appreciated!

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

export default function App() {
  const [time, setTime] = useState(0)
  let t;
  function startTime(){
    t = setInterval(()=>{
      setTime(time 1);
    },1000)
  }
  function stopTime(){
    clearInterval(t);
  }
  return (
    <div className="App">
      <h1>{time}</h1>
      <button onClick={startTime}>Start</button>
      <button onClick={stopTime}>Stop</button>
    </div>
  );
}

CodePudding user response:

As you did, on first click you create a function in memory that will call setTime(0 1) for ever, as 0 is the value of time when you registered that function in memory. To have the updated time, you would wanna pass a function to setTime.

Also, to memoize the interval reference, you should be using a React ref, as a normal variable will come to its initial value at each render. Here is a working example on CodeSandbox and the code below:

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

export default function App() {
  const [time, setTime] = useState(0)
  const timerRef = useRef();
  function startTime(){
    timerRef.current = setInterval(()=>{
      setTime(time =>time 1);
    },1000)
  }
  function stopTime(){
    clearInterval(timerRef.current);
  }

  return (
    <div className="App">
      <h1>{time}</h1>
      <button onClick={startTime}>Start</button>
      <button onClick={stopTime}>Stop</button>
    </div>
  );
}
  • Related