javascriptreactjsrxjsjavascript-date

How can I increase the variable in the background using Date() in react js?


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

EDIT: I need the timer to be remembered when the tab is completely closed, and as a result, when restarting, the timer value was added to the original value of the timer value and the effect of working in the background was obtained (as in many games where there are daily rewards)


Solution

  • I would suggest you calculate the difference between the current time and the last restore time whenever the tab is reopened. This way, you can restore the energy based on the elapsed time since the tab was last open making sure that any energy restoration that should have happened while the tab was closed is applied as soon as the tab is reopened

        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;
            const energyToRestore = Math.floor(timeSinceLastRestore / 10);
    
            if (energyToRestore > 0) {
              const currentEnergy = parseInt(localStorage.getItem("strong")) || 
                  200;
              const restoredEnergy = currentEnergy + energyToRestore;
              localStorage.setItem("strong", restoredEnergy);
              setStrong(restoredEnergy);
              localStorage.setItem("lastRestoreTime", now.toString());
            }
          } else {
            localStorage.setItem("strong", 200);
            localStorage.setItem("lastRestoreTime", now.toString());
          }
        }
    
        useEffect(() => {
          restoreEnergy(); 
    
          const intervalId = setInterval(() => {
            restoreEnergy();
          }, 10000); 
    
          return () => clearInterval(intervalId);
        }, []);
    
        return (
    
        );
      }