sessionStorage 上的计时器在刷新时停止

timer on sessionStorage stop on refresh

我正在做一个存储在 sessionStorage 中的计时器,但是如果刷新页面,计时器就会停止!请帮忙

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);
}

这里的getItem("timer")只是为了检查定时器是否结束,我在另一个方法中使用这个定时器

感谢

即使页面重新加载,SessionStorage 仍然存在。读这个:https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

你应该做的是,你刷新页面后,再次从SessionStorage中获取Timer的值,然后再次调用该方法。

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);
}