I have written code that should increment the strong variable every 10 seconds in the background using module Date()
import React, { useState, useEffect } from "react";
export default function App() {
const [strong, setStrong] = useState(200);
function restoreEnergy() {
const now = Math.floor(Date.now() / 1000);
const lastRestoreTime = parseInt(localStorage.getItem("lastRestoreTime"));
if (lastRestoreTime) {
const timeSinceLastRestore = (now - lastRestoreTime) / 10;
if (timeSinceLastRestore >= 10) {
const currentEnergy = parseInt(localStorage.getItem("strong"));
const restoredEnergy = Math.floor(currentEnergy + timeSinceLastRestore / 10);
localStorage.setItem("strong", restoredEnergy);
setStrong(restoredEnergy);
localStorage.setItem("lastRestoreTime", now.toString());
}
} else {
localStorage.setItem("strong", 200);
localStorage.setItem("lastRestoreTime", now.toString());
}
}
useEffect(() => {
const lastRestoreTime = localStorage.getItem("lastRestoreTime");
const intervalId = setInterval(restoreEnergy, 10000);
return () => clearInterval(intervalId);
}, []);
return ({strong})
}
It only works when the tab is open, but not in the background, why?
I tried to use different mathematical actions to get the desired result, but they didn’t work
New contributor
Федя Равчеев is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.