0

I'm implementing countdown using Vanilla JS and I'd like to know how do I ensure that it doesn't reset each time I refresh the page.

Am I missing something here? As for now, it will reset to 30 days each time I reload the page.

const countDownClock = (number = 100, format = 'seconds') => {

  const daysElement = document.querySelector('.days');
  const hoursElement = document.querySelector('.hours');
  const minutesElement = document.querySelector('.minutes');
  const secondsElement = document.querySelector('.seconds');
  let countdown;
  convertFormat(format);

  function convertFormat(format) {
    switch (format) {
      case 'seconds':
        return timer(number);
      case 'minutes':
        return timer(number * 60);
      case 'hours':
        return timer(number * 60 * 60);
      case 'days':
        return timer(number * 60 * 60 * 24);
    }
  }

  function timer(seconds) {
    const now = Date.now();
    const then = now + seconds * 1000;

    countdown = setInterval(() => {
      const secondsLeft = Math.round((then - Date.now()) / 1000);

      if (secondsLeft <= 0) {
        clearInterval(countdown);
        return;
      };

      displayTimeLeft(secondsLeft);

    }, 1000);
  }

  function displayTimeLeft(seconds) {
    daysElement.textContent = Math.floor(seconds / 86400);
    hoursElement.textContent = Math.floor((seconds % 86400) / 3600);
    minutesElement.textContent = Math.floor((seconds % 86400) % 3600 / 60);
    secondsElement.textContent = seconds % 60 < 10 ? `0${seconds % 60}` : seconds % 60;
  }
}

countDownClock(30, 'days');
mplungjan
  • 169,008
  • 28
  • 173
  • 236
yansusanto
  • 355
  • 1
  • 6
  • 13
  • Use the browser's [local storage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) to persist state – vsync May 31 '20 at 16:30
  • Everything would start from the beginning at each refresh, you can write a function to store the value at local storage but I don't think it would be very efficient. – Berk Kurkcuoglu May 31 '20 at 16:32
  • I made you a snippet. Please add relevant HTML – mplungjan May 31 '20 at 16:32
  • I don't understand why this question is considered a duplicate, I wouldn't have asked if I know how to use local storage. – yansusanto May 31 '20 at 16:40
  • Local storage is one of the ways to save data to the browser. You could also use document.cookie. The question is about saving, so you can retrieve data after refreshing page. – Anthony May 31 '20 at 16:46

0 Answers0