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