Save timer time when restarting page

Asked

Viewed 38 times

1

I’m making a countdown timer in Javascript that after 3 days it restarts the countdown, but I wonder how I can make the countdown not restart when reloading the page.

let time = new Date();
let finalDate = new Date();
finalDate.setDate(time.getDate()+3);

setInterval(function() {
    time = new Date();
    finalDate = new Date();
    finalDate.setDate(time.getDate()+3);
    console.log('Funcionou')
}, 259200000)

let now, timeLeft, timeString;

let timer = setInterval(function() {
    now = Date.now();
    dateDiff = finalDate - now;
    timeLeft = new Date(dateDiff);
    
    timeString = timeLeft.toLocaleTimeString (
    'pt-BR', 
        {   
            hour12: false, 
            minute: '2-digit', 
            second: '2-digit', 
            hour: '2-digit', 
            day: '2-digit', 
            timeZone: 'GMT'
        }
    )

    $('.timer .count-timer .days').text(timeString.split(':')[0].split(" ")[0]);
    $('.timer .count-timer .hours').text(timeString.split(':')[0].split(" ")[1]);
    $('.timer .count-timer .minutes').text(timeString.split(':')[1]);
    $('.timer .count-timer .seconds').text(timeString.split(':')[2]);
}, 1000)
  • please enter more details. What is the variable you want to save?

  • Tried to save the finalDate in a localStorage, for example, and consult it every time the page is reloaded? I was confused in the use of setInterval

  • Very cool your question! : -D I’ll follow here to see what the guys will answer ;-) It’s been over 100 years that I don’t touch the web and I’m a little rusty. If you create a cookie to store the date and read when the user reloads the page does not work?

  • 1

    I’d like to save the finale

  • This localStorage solution I even thought about doing, but when a new user access the page the timer will restart again not ? pq localStorage will not exist

  • @Luizfelipedasilva there you will need a backend, can use google firebase if you do not want to do one of 0

Show 1 more comment

1 answer

2

To save and read the date locally you can use the localStorage:
Saving:
localStorage.setItem('data', finalDate.toString())
Reading:
finalDate = new Date(localStorage.getItem('data'))
Case localStorage.getItem('data') for null, you start finalDate normally.

But from what I understand, you want to save for all users. Then you will need a back-end to save and read the date from the server. You don’t need to create a back-end just for this, you can use existing free solutions like the Google Firebase.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.