Search code examples
javascriptcountdowntimersession-storage

timer on sessionStorage stop on refresh


I am doing a timer that I store in a sessionStorage but if a refresh the page the timer stop! some help please

function time (secondes) {
    const temps = Date.now();
    const apres = temps + secondes * 1000;
    const timer = setInterval(() => {
        const secondsLeft = Math.round((apres - Date.now()) / 1000)
        if (secondsLeft < 0) {
            clearInterval(timer);
            sessionStorage.clear();
            if (sessionStorage.getItem('Timer') === null) {
                $(".reservation").css("display", "none");
            }
            return;
        }
        sessionStorage.setItem("Timer", secondsLeft)
    }, 1000);
}

the getItem("timer") here is just to check if the timer is over, I am using this Timer item in another method

thx


Solution

  • SessionStorage persist even if the page reloads. Read this:https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

    What you should do is, after you refresh the page, get the value of Timer again from SessionStorage and then again call the method.

    function time (secondes) {
    const temps = Date.now();
    const apres = temps + secondes * 1000;
    const timer = setInterval(() => {
        const secondsLeft = Math.round((apres - Date.now()) / 1000)
        if (secondsLeft <= 0) {
            clearInterval(timer);
            sessionStorage.clear();
            //you dont need below if condition as secondsLeft is already 0. Commented if condition.
            //if (sessionStorage.getItem('Timer') === null) {
                $(".reservation").css("display", "none");
            //}
            return;
        }
        else{
          //update the div content and show the current timer value in the div or in the span inside the div. (write a separate function for this).
        }
        sessionStorage.setItem("Timer", secondsLeft)
        }, 1000);
    }
    
    //Method to call after page load:
    function startTimerOnPageLoad(){
         var x = parseInt( sessionStorage.getItem('Timer'));
         //put a check, Timer is present in sessionStorage and x is not undefined. I've not added it here purposely.
         time(x);
    }