Add javascript countdown to localstorage

Asked

Viewed 78 times

-1

I made a countdown using javascript, which is working fine. However, when adding the event, he wanted to record it in localstorage and allow it to be done more than once, adding several events and having everyone get their countdown to work. If anyone can give me a hint as to how I can implement this, I am most grateful.

let contador = document.getElementById('contador');

function agendar() {
  let nomeEvento = document.getElementById('nomeEvento').value;
  if (!nomeEvento) {
    document.getElementById('contador').innerText = 'Insira um nome para agendar seu evento'
  } else {
    let data = document.getElementById('date').value.split('-');
    let hour = document.getElementById('time').value.split(':');

    let dataEvent = new Date(...data, ...hour);
    dataEvent.setMonth(dataEvent.getMonth() - 1);


    let timer = setInterval(function() {

      let contagem = dataEvent.getTime();
      let atual = new Date().getTime();
      let distance = contagem - atual;

      let dias = Math.floor(distance / 86400000);
      let horas = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      let minutos = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
      let segundos = Math.floor((distance % (1000 * 60)) / 1000);


      let formata = `{${nomeEvento}} começa em \n ${dias} dias \n ${horas < 10 ? '0' + horas : horas}h : ${minutos < 10 ? '0' + minutos : minutos}m : ${segundos < 10 ? '0' + segundos : segundos}s`;
      contador.innerText = formata;

      if (dias == 0 & horas == 0 & minutos == 0 & segundos == 0) {
        clearInterval(timer)
        contador.innerText = `o ${nomeEvento} começou`;
      }
      if (dias < 0) {
        contador.innerText = 'Data ou hora inválida(s)';
        clearInterval(timer)
      }

    }, 1000)
  }


}
<div class="container">
  <form action="" class="form content">
    <input type="text" name="" id="nomeEvento" placeholder="Nome do Evento">
    <p>Data e hora do evento</p>
    <input type="date" name="" id="date">
    <input type="time" name="" id="time"> <br>
    <button type="button" onclick="agendar()">Iniciar</button>
  </form>
  <div id='contador' />
</div>

  • I suggest you save the "Event" in Localstorage and rescue when opening the page. So you calculate the missing time when it is displayed, in the same way you do when you click on "Start". What is your question exactly? Don’t know how to store in Localstorage or was thinking of changing the "record" every second?

  • @Rafaeltavares, my doubt is what to add to the localStorage, and at what time of the execution, at first I thought about saving the whole timer, but I don’t know exactly how to do or if it is feasible, or if I create an object to store the different events. I’m a little lost kkkkkk. So I wanted an idea

1 answer

1

To save to localStorage you need the key to be a Domstring, but you do not have access to all keys you need your program to remember the key, your alternative is to map in a object or array and store in a JSON string, which you can access, iterate and restart the event count.
The date can be saved on ISOString or the valueOf, the 2 options are feasible to re-create the object. Your code can be adapted to the following structure:

let eventos = [ ['ev1Name', new Date().toISOString()], ['ev2Name', new Date().toISOString()] ];
// salva no storage em string
localStorage.setItem('agenda', JSON.stringify(eventos));

function checaAgenda() {
  let agenda = localStorage.getItem('agenda');
  eventos = agenda ? JSON.parse(agenda) : [];
  for (const evento of eventos) {
    iniciaContagem(evento);
  }
}

function iniciaContagem(evento) {
  // aqui o código da agenda
  console.log(evento[0], new Date(evento[1]));
}

// teste no console
eventos = [];
checaAgenda();

Browser other questions tagged

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