Javascript countdown that persists across page refresh

131 views Asked by At

I am trying to make a countdown, which do not restart after refreshing this page. I am using keith wood countdown. I want to count to 5 minutes.

var countdownTarget = localStorage.getItem('countdownTarget');
    if (countdownTarget === null) 
    {
        var countdownTarget = new Date();
        countdownTarget = new Date(countdownTarget.getFullYear(), countdownTarget.getMonth(), countdownTarget.getDate(), countdownTarget.getHours(), countdownTarget.getMinutes() + 5, countdownTarget.getSeconds());
        localStorage.setItem('countdownTarget', countdownTarget);
    }

    $('#defaultCountdown').countdown({ until : countdownTarget, format: 'MS', compact: true});

I am saving the current date + 5 minutes to browser local storage as countdownTarget (only if it was not done before). And if an user refresh the page, the time should be persistent. But there is problem. When I load the page for the first time, the time is counting from 5 minutes (that should be normal), but when I am trying to refresh it again it starts counting from 36 minutes and I do not know why and I do not know where these 36 minutes came from.

1

There are 1 answers

0
Chris Thorsvik On

Instead of re-declaring the date, why not just increment the minutes? Your code worked for me. Also, you should only initiate countdownTarget once.

var countdownTarget = localStorage.getItem('countdownTarget');
if (countdownTarget === null) {
    countdownTarget = new Date();
    countdownTarget.setMinutes(countdownTarget.getMinutes() + 5);
    localStorage.setItem('countdownTarget', countdownTarget);
} else {
    countdownTarget = new Date(countdownTarget);
}
$('#defaultCountdown').countdown({ until : countdownTarget, format: 'MS', compact: true});