Home > front end >  Call function when time changes in react
Call function when time changes in react

Time:09-06

Being new to react , this all is really confusing and new to me , so I apologise if I'm making some obvious oversight.

Im making a stopwatch and implementing the seconds for starters. However; Im confused as to how i'll implement the on display seconds number to update when each second passes.

This is what I'm doing right now

function App() {
  const [time , updateTime] = React.useState(0);
  var startsec = 0;

  
  //UpdateTime should get triggered when next second passes
  const UpdateTime = () => {
    //Update time variable with the new seconds elapsed
  }

  //Should run every second or something
  const CheckTimeUpdation = () => {
    currentsec = Math.floor(Date.now() / 1000.0);
    console.log(currentsec);
    if(currentsec > startsec){
      UpdateTime(currentsec-startsec);
    }
  }

  const GetStartTime = () => {
    startsec = Math.floor(Date.now() / 1000.0);
  }

  //Clock component just gets a number and displays it on the screen
  return (<div className = "App">
    <Clock timerSeconds= {time}/>
    <div>
      <button onClick={GetStartTime}></button>
    </div>
    </div>);

}

export default App;


Date.now() function gets the miliseconds passed since 1970 (hence the division by 1000 to make them into seconds) and I find the difference between when the button was clicked and current one and passs that to the time component to display.

How do I make the CheckTimeUpdation function run every second or so?

CodePudding user response:

You can use setInterval in the GetStartTime Function.

const GetStartTime = () => {
    startsec = Math.floor(Date.now() / 1000.0);
    setInterval(() => CheckTimeUpdation(), 1000);
  }

CodePudding user response:

What you want is the setInterval() method (see: https://developer.mozilla.org/en-US/docs/Web/API/setInterval)

However your code so far has some issues:

On the button click, getStartTime runs and it updates the value of startsec. Firstly, this does not cause the component to re-render, and so the component will not update and you will see nothing changing on your screen. Also, if you did get your component to re-render, you will notice that startsec will be 0 again on the next re-render, so re-assigning startsec like how you did likely doesn't do what you want it to. If you want to persist values between rerenders, you can use useState (https://reactjs.org/docs/hooks-reference.html#usestate) or useRef (https://reactjs.org/docs/hooks-reference.html#useref).

Now i'm assuming you want to start the timer when the button is clicked. What you need is to start the interval (via setInterval) on the button click, and update time every 1000ms.

You'd also want to clear the interval once you don't need it anymore, using the clearInterval() method. You'll need to save the id returned from setInterval() initially in order to clear it later.

Below I have written a short example using this idea with setInterval on button click to help you:

import { useState, useRef } from "react";

export default function App() {
  const [timerState, setTimerState] = useState("paused");
  const [timeElapsed, setTimeElapsed] = useState(0);
  const intervalId = useRef(0);

  const isRunning = timerState === "running";
  const isPaused = timerState === "paused";

  const onStartTimer = () => {
    intervalId.current = setInterval(() => {
      setTimeElapsed((time) => time   1);
    }, 1000);
    setTimerState("running");
  };

  const onStopTimer = () => {
    clearInterval(intervalId.current);
    intervalId.current = 0;
    setTimerState("paused");
  };

  const onClearTimer = () => {
    setTimeElapsed(0);
  };

  return (
    <div className="App">
      <h1>{timeElapsed}</h1>
      {isPaused && <button onClick={onStartTimer}>Start timer</button>}
      {isRunning && <button onClick={onStopTimer}>Stop timer</button>}
      {!!timeElapsed && <button onClick={onClearTimer}>Clear timer</button>}
    </div>
  );
}

  • Related