0

I am using Electron + React trying to set up a stopwatch timer that updates the price value by certain amount every second using useState hook . the component works fine when the window is open . The problem is when the window is minimized the counter freezes and when i open the window back up it resumes. here's the code for the component:

import React, { useState } from "react";
import BtnComponent from './BtnComponent';
import DisplayComponent from './DisplayComponent';
import "../index.css";

function Timer(props) { 
 


  const [price, setPrice] = useState(0);
  const [time, setTime] = useState({ ms: 0, s: 0, m: 0, h: 0 });
  const [interv, setInterv] = useState();
  const [status, setStatus] = useState(0);
  const start = () => {
    run();
    setStatus(1);
    setInterv(setInterval(run, 10));
  };

  var updatedMs = time.ms,
    updatedS = time.s,
    updatedM = time.m,
    updatedH = time.h,
    updatedP = price;

  const run = () => {
    if (updatedM === 60) {
      updatedH++;
      updatedM = 0;
    }
    if (updatedS === 60) {
      updatedM++;
      updatedS = 0;
    }
    if (updatedMs === 100) {
      updatedS++;
      updatedMs = 0;
      updatedP = updatedP + ((220 / 60)/60);
    }
    updatedMs++;
     
    
    return (
      setTime({ ms: updatedMs, s: updatedS, m: updatedM, h: updatedH }),
      setPrice(parseInt(updatedP)));
  };


  const stop = () => {
    clearInterval(interv);
    setStatus(2);

  };

  const reset = () => {
    clearInterval(interv);
    setStatus(0);
    setTime({ ms: 0, s: 0, m: 0, h: 0 });
    setPrice(0);
  };

  const resume = () => start();


  return (
    <div className="clock-holder">
      <div className="stopwatch">
        <DisplayComponent
          time={time}
          price={price}
          posteid={props.post}
          img={props.img}
          color={props.color}
        />
        <BtnComponent
          status={status}
          resume={resume}
          reset={reset}
          stop={stop}
          start={start}
        />
      </div>
    </div>
  );
}

export default Timer

  • 1
    you could try https://stackoverflow.com/questions/59557854/setinterval-stops-after-an-hour-with-electron – Rob Welan Nov 12 '21 at 23:59
  • one problem i can see is that, you can't use a state for `interv`, try to use a `useRef`, because you don't want to update whenever the `interv` changes. – windmaomao Nov 13 '21 at 14:26

0 Answers0