Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

115
Views
how to save a variable with the current data saved in an interval updating state

I am builidng a typicall stopwatch/clock app in here.

The issue: When clicking Pause Button then Split Button (which prints the elapsed time) and then start back, both the stopwatch and the printed time restart. That is because I am saving the Crono time in the handleClickSplit function. Any ideas on the best way to save that current paused time to prevent the bug?

This is the image

enter image description here

This is my code:

export default function Home({ enableCrono }) {
  const [cronoTime, setCronoTime] = useState({ h: 0, m: 0, s: 0, ms: 0 });
  const [printTime, setPrintTime] = useState([]);
  const [interv, setInterv] = useState();
  const [status, setStatus] = useState(0);
  // 0 => not running
  // 1 => start
  // 2 => pause
  // 3 => stop

  const start = () => {
    if (cronoTime.m === 60) {
      cronoTime.h++;
      cronoTime.m = 0;
    }
    if (cronoTime.s === 60) {
      cronoTime.m++;
      cronoTime.s = 0;
    }
    if (cronoTime.ms === 100) {
      cronoTime.s++;
      cronoTime.ms = 0;
    }
    cronoTime.ms++;
    return setCronoTime({
      ms: cronoTime.ms,
      s: cronoTime.s,
      m: cronoTime.m,
      h: cronoTime.h,
    });
  };

  const handleClickStart = () => {
    start();
    setStatus(1);
    setInterv(setInterval(start, 10));
  };
  const handleClickStop = () => {
    clearInterval(interv);
    setStatus(3);
  };
  const handleClickPause = () => {
    clearInterval(interv);
    setStatus(2);
  };

  const handleClickClear = () => {
    clearInterval(interv);
    setStatus(0);
    setCronoTime({ h: 0, m: 0, s: 0, ms: 0 });
    setPrintTime([]);
  };

  const handleClickSplit = () => {
    setPrintTime((prevtime) => [...prevtime, cronoTime]);

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You're saving in your printTime array a reference to the very same cronoTime object. Just save a new object, so that changes on cronoTime do not propagate to the object in printTime:

setPrintTime((prevtime) => [...prevtime, {...cronoTime}]);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!