How to do a countdown with jQuery that restarts weekly

Asked

Viewed 343 times

0

I have to do a countdown for a promotion.

I need this counter to restart every Tuesday at 00:00 hours so it looks something like this:

"Only 6 days left 12 hours 42 minutes and 37 seconds left until the promotion ends"

  • 1

    You need to pick the difference between the current moment and next Tuesday...

  • Interesting idea, but I have no experience in jQuery, there is a way to always get the timestamp next "Tuesday"?

  • Here’s how to mark a response as accepted at http://i.stack.Imgur.com/jx7Ts.png and why at https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079

  • Because in jquery?

2 answers

1

I have to do a countdown for a promotion.

<!-- Display the countdown timer in an element -->

// Set the date we're counting down to
var countDownDate = new Date("Jan 5, 2019 15:37:25").getTime();

// Update the count down every 1 second
var x = setInterval(function() {

  // Get todays date and time
  var now = new Date().getTime();

  // Find the distance between now and the count down date
  var distance = countDownDate - now;

  // Time calculations for days, hours, minutes and seconds
  var days = Math.floor(distance / (1000 * 60 * 60 * 24));
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);

  // Display the result in the element with id="demo"
  document.getElementById("demo").innerHTML = days + "d " + hours + "h " +
    minutes + "m " + seconds + "s ";

  // If the count down is finished, write some text 
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }
}, 1000);
<p id="demo"></p>

I need this counter to restart every Tuesday at 00:00 hours

Here you will set the limit of the counter:

// Set the date we're counting down to
var countDownDate = new Date("Jan 5, 2019 15:37:25").getTime();

Remember that this is only the client side (front-end). You must validate the server-side date/time (back-end).

W3schools: How TO - Javascript Countdown Timer

1


//função para definir o dia destino e horário desejado para o final da promoção de cada semana
function dataDiaDaSemana(diaRef){
    var dias = {
        segunda: 1,
        terca: 2,
        quarta: 3,
        quinta: 4,
        sexta: 5,
        sabado: 6,
        domingo: 0
    };
    
    var dataAtual = new Date();
    var timestampAtual = dataAtual.getTime();
    var diaGatilho = dias[diaRef];
    var diaMilisegDif=0;
    var diaEmMiliseg = 1000*60*60*24;
    // adiciona um dia a diaMilisegDif enquanto o diaRef desejado (terca por exemplo) não for atingido
    while(dataAtual.getDay()!=diaGatilho){
        diaMilisegDif += diaEmMiliseg;
        dataAtual = new Date(dataAtual.getTime()+diaEmMiliseg);
    }
    return new Date(timestampAtual + diaMilisegDif);
}

//defina o dia destino da semana
var dia = dataDiaDaSemana("terca");
//defina o horario
dia.setHours(0,0,0,0); //(hora, min, seg, miliseg)


//fonte https://www.w3schools.com/howto/howto_js_countdown.asp

//define a data para contagem regressiva
var countDownDate = new Date(dia).getTime();

// Update the count down every 1 second
var x = setInterval(function() {

  // Get todays date and time
  var now = new Date().getTime();

  // Find the distance between now and the count down date
  var distance = countDownDate - now;

  // Time calculations for days, hours, minutes and seconds
  var days = Math.floor(distance / (1000 * 60 * 60 * 24));
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);
  
  	if (distance < 1) { // você chegou ao seu destino :-)
		document.getElementById("demo").innerHTML = "";
		/*** redefine a data para próximo dia destino da semana *****/
		countDownDate = new Date(countDownDate.valueOf() + 604800000);
  	}else if (days>0){
		document.getElementById("demo").innerHTML = "Restam apenas " + days + "d " + hours + "h "
		+ minutes + "m " + seconds + "s para o fim da promoção";
	}else if (hours==0 && minutes==0){
		document.getElementById("demo").innerHTML ="Restam apenas " + seconds + "s para o fim da promoção";
	}else if (hours==0){
		document.getElementById("demo").innerHTML ="Restam apenas " + minutes + "m " + seconds + "s para o fim da promoção";
	}else{
		document.getElementById("demo").innerHTML ="Restam apenas " + hours + "h "+ minutes + "m " + seconds + "s para o fim da promoção";
	}
		
}, 1000);
<p id="demo"></p>

For a quick test put var dia = dataDiaDaSemana("...."); being .... today and in dia.setHours(0,0,0,0); current time and one minute after the current minute example, if they are 12:25 place dia.setHours(12,26,0,0);

  • Perfect, that’s just what I needed, thank you very much, really, saved my kk day

  • @Danielhirt for a quick test place var dia = dataDiaDaSemana("sabado"); and in dia.setHours(0,0,0,0); current time one minute after the current minute example, if it is 12:25 put dia.setHours(12,26,0,0);

Browser other questions tagged

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