Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 (

    );
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading