Hi, I’m trying to build a browser extension which runs a countdown timer. Now browser extensions reloads every time the user closes and opens the popup window again. Hence I have used localStorage to keep track of the state values.
Problem: Let’s say I close the popup window when the timer was at 10:00
. After 30 seconds, when I open the popup window, the timer will for a second show 10:00
and then it would change to 09:30
and the countdown will begin.
I know it is happening because the timer is reading the initial values from the localStorage after every render but I can’t figure out the way to directly show the current timer state.
Would someone please suggest how do I fix this?
Here is the relevant code:
const FocusModeView2 = (props) => {
let minsLeftLocal = parseInt(localStorage.getItem("minsLeft"));
let secsLeftLocal = parseInt(localStorage.getItem("secsLeft"));
const [minsLeft, setMinsLeft] = useState(minsLeftLocal);
const [secsLeft, setSecsLeft] = useState(secsLeftLocal);
const [progress, setProgress] = useState(0);
const styles = focusModeView2Styles(progress);
useEffect(() => {
let startTime = parseInt(localStorage.getItem("startTime"));
let focusPeriod = parseInt(localStorage.getItem("focusPeriod"));
let timeLength = focusPeriod * 60 * 1000; // in milliseconds
let timerLengthInSecs = props.focusPeriod * 60;
let endTime = startTime + timeLength;
let timer = setInterval(() => {
let currentTime = Date.now();
let newMinsLeft = Math.floor((endTime - currentTime) / (1000 * 60));
let newSecsLeft = Math.round(((endTime - currentTime) / 1000) % 60);
newSecsLeft = newSecsLeft === 60 ? 0 : newSecsLeft;
let totalSecsLeft = newMinsLeft * 60 + newSecsLeft;
setMinsLeft(newMinsLeft);
setSecsLeft(newSecsLeft);
localStorage.setItem("minsLeft", newMinsLeft);
localStorage.setItem("secsLeft", newSecsLeft);
let currentProgress =
((timerLengthInSecs - totalSecsLeft) / timerLengthInSecs) * 360;
setProgress(currentProgress);
if (newMinsLeft <= 0 && newSecsLeft <= 0) {
clearInterval(timer);
props.resetTimer();
}
}, 1000);
}, []);
return (
<div>
<div className={styles.timer}>
{minsLeft < 10 ? `0${minsLeft}` : minsLeft} :{" "}
{secsLeft < 10 ? `0${secsLeft}` : secsLeft}
</div>
<div className={styles.progressBar}></div>
</div>
);
};
export default FocusModeView2;
Here’s the github repo for the same:GitHub - pragyes31/focus-sutra