haestan
haestan

Reputation: 93

SessionStorage and reloading page javascript

I'm trying to keep information (timer) in sessionStorage key. I would like to keep timer runing if user reload the page.

I tried something like this

    var timer = 50;
    sessionStorage.setItem('timer_station', timer);
    var timer_data = sessionStorage.getItem('timer_station');
    var interval = setInterval(function () {
        timer_data--;
        console.log(timer_data);
        $('#count-timer').text(timer_data);
        if (timer_data === 0) {
            $('#count-timer').text('Désolé, votre réservation a expirée');
            clearInterval(interval);
            sessionStorage.clear();
        }
    }, 1000);
},

But when i'm reloading the page, timer reset. Thanks a lot :)

Upvotes: 0

Views: 1364

Answers (2)

folktrash
folktrash

Reputation: 186

This is because you're setting the timer_station value on each reload. You want to move the setItem into an if check. Something like...

var interval = setInterval(function () {
if (isThereATimerStationAlreadySetCheck) {
  //do stuff with it
} else {
  //set it
}

}, 1000);

Upvotes: 1

Chris Charles
Chris Charles

Reputation: 4446

Firstly we need to handle the case that they haven't been here before:

var timer = sessionStorage.getItem('timer_station');
if (!timer){
    timer = 50
}

Then do our interval, saving the new time left as we go:

var interval = setInterval(function () {
    timer--;
    console.log(timer);
    sessionStorage.setItem('timer_station', timer);
    $('#count-timer').text(timer);
    if (timer === 0) {
        $('#count-timer').text('Désolé, votre réservation a expirée');
        clearInterval(interval);
        sessionStorage.clear();
    }
}, 1000);

Upvotes: 2

Related Questions