skip to Main Content

I want to calculate the time a user goes offline.

Am creating a mining app and I want the mining to continue even if the user goes offline, am saving the date to the localStorage every second to be able to calculate how many seconds has elapsed when user is offline so I can calculate the amount the user ought to have accumulated if the user were to be online

2

Answers


  1. First save the timestamp regularly: Store the current timestamp in localStorage at regular intervals while the user is online.

    Then we should calculate the offline duration: When the user comes back online, retrieve the last saved timestamp from localStorage and calculate the elapsed time.

    Finally we can get the elapsed time to determine how much progress should have been made while the user was offline.

    You can do that, when page loads

    useEffect(() => {
        const saveTimestamp = () => {
          localStorage.setItem('lastOnlineTimestamp', Date.now().toString());
        };
    

    this useEffect will save curent time to the local storage variable called "lastOnlineTimestamp".

    Then update that time regularly, Here I have assigned 1Seconds. here 1000 means 1000ms.

    const interval = setInterval(saveTimestamp, 1000);
    

    Now whenthe user goes offline, we can get that time like this

     window.addEventListener('beforeunload', saveTimestamp);
    

    You can get more details for this event handler from this documentation. Link

    When a user again online, we can calculate elapsed time by this,

     const lastTimestamp = localStorage.getItem('lastOnlineTimestamp');
         const elapsedTime = Math.floor((Date.now() - parseInt(lastTimestamp, 10)) / 1000);
    
    Login or Signup to reply.
  2. To accomplish this task, you’ll need a few steps:

    • Save the current time every second to localStorage when the user is online.
    • Detect when the user goes offline and store the offline time.
    • Detect when the user comes back online and calculate the elapsed time.
    • Calculate the amount mined during the offline period based on the elapsed time.
    • Update the total mined amount.
    // Define mining rate
    const MINING_RATE_PER_SECOND = 0.01;
    
    // Save the current time to localStorage every second
    setInterval(() => {
        localStorage.setItem('lastOnlineTime', Date.now().toString());
    }, 1000);
    
    // Event listener for when the user goes offline
    window.addEventListener('offline', () => {
        localStorage.setItem('offlineTime', Date.now().toString());
    });
    
    // Event listener for when the user comes back online
    window.addEventListener('online', () => {
        const offlineTime = parseInt(localStorage.getItem('offlineTime') || '0', 10);
        const currentTime = Date.now();
    
        // Calculate the elapsed time in seconds
        const elapsedTime = (currentTime - offlineTime) / 1000;
    
        // Calculate the mined amount during offline time
        const minedAmount = elapsedTime * MINING_RATE_PER_SECOND;
    
        // Retrieve the total mined amount from localStorage
        const totalMined = parseFloat(localStorage.getItem('totalMined') || '0');
    
        // Update the total mined amount
        const updatedTotalMined = totalMined + minedAmount;
    
        // Save the updated total mined amount back to localStorage
        localStorage.setItem('totalMined', updatedTotalMined.toString());
    
        // Clear the offlineTime since the user is now online
        localStorage.removeItem('offlineTime');
    });
    
    // Retrieve and display the total mined amount (for demonstration purposes)
    function displayTotalMined() {
        const totalMined = parseFloat(localStorage.getItem('totalMined') || '0');
        console.log(`Total Mined: ${totalMined}`);
    }
    
    // Example: Display the total mined amount every 5 seconds
    setInterval(displayTotalMined, 5000);
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search