таймер на sessionStorage остановка при обновлении - PullRequest
0 голосов
/ 01 октября 2019

Я делаю таймер, который храню в 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 («таймер») здесь просто чтобы проверить, истек ли таймер, я использую этот элемент таймера в другом методе

thx

1 Ответ

0 голосов
/ 01 октября 2019

SessionStorage сохраняется даже после перезагрузки страницы. Прочитайте это: https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

Что вы должны сделать, это после того, как вы обновите страницу, снова получите значение Timer из 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();
        //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);
}
...