Negative timer when arriving at the final date

Asked

Viewed 17 times

2

I am using a timer that is working well, the only problem is that when it Zera it starts to count on the negative and I want it to stay stationary at zero, follows the code:

    <script>
   var target_date = new Date("november 27, 2020").getTime();
   var dias, horas, minutos, segundos;
   var regressiva = document.getElementById("regressiva");

   setInterval(function () {

   var current_date = new Date().getTime();
   var segundos_f = (target_date - current_date) / 1000;

   dias = parseInt(segundos_f / 86400);
   segundos_f = segundos_f % 86400;

  horas = parseInt(segundos_f / 3600);
  segundos_f = segundos_f % 3600;

  minutos = parseInt(segundos_f / 60);
  segundos = parseInt(segundos_f % 60);

  document.getElementById('dia').innerHTML = dias;
  document.getElementById('hora').innerHTML = horas;
  document.getElementById('minuto').innerHTML = minutos;
  document.getElementById('segundo').innerHTML = segundos;


  }, 1000);
  </script>

How do I stop him at zero and not negatively?

1 answer

3


Simple, check if the difference between the current_date and the target_date is less than zero if you don’t execute the logic and stop the interval:

var target_date = new Date("november 27, 2020").getTime();
var dias, horas, minutos, segundos;
var regressiva = document.getElementById("regressiva");

var intervalRef = null;

intervalRef = setInterval(function () {
  var current_date = new Date().getTime();

  if ((target_date - current_date) <= 0) {
    document.getElementById('dia').innerHTML = 0;
    document.getElementById('hora').innerHTML = 0;
    document.getElementById('minuto').innerHTML = 0;
    document.getElementById('segundo').innerHTML = 0;
    clearInterval(intervalRef);
    return;
  }

  var segundos_f = (target_date - current_date) / 1000;

  dias = parseInt(segundos_f / 86400);
  segundos_f = segundos_f % 86400;

  horas = parseInt(segundos_f / 3600);
  segundos_f = segundos_f % 3600;

  minutos = parseInt(segundos_f / 60);
  segundos = parseInt(segundos_f % 60);

  document.getElementById('dia').innerHTML = dias;
  document.getElementById('hora').innerHTML = horas;
  document.getElementById('minuto').innerHTML = minutos;
  document.getElementById('segundo').innerHTML = segundos;


}, 1000);

Browser other questions tagged

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