How do I make a stopwatch down to a date?

4

Well this is the following I have a following date with one hour, and I would like to know how I could make a descending stopwatch, with days hours minutes and seconds until I get to that date and time.

Example: The date set in the javascript is 18/08/2016 at 20:02 and 16 seconds, ie the timer will have to show decreasingly how many days, hours, and seconds are missing until arriving at that date with counting down in time real.

How can I do this with javascript?

Thank you.

    
asked by anonymous 16.08.2016 / 00:16

2 answers

1

You can use some library of Countdown , below follows an implementation used the library developed by Hugo Giraudel

Countdown.js

new Countdown({
  selector: '#countdown',
  msgAfter: "O Evento Iniciou!",
  msgPattern: "{days} dias, {hours} horas, {minutes} minutos e {seconds} segundos até a data do evento!",
  dateEnd: new Date("2016-08-18T20:02:16"),
  onEnd: function() {
    alert('O Evento Iniciou!');
  }
});
<script src="https://rawgit.com/HugoGiraudel/Countdown.js/master/countdown.js"></script><divid="countdown"></div>
    
16.08.2016 / 15:30
1

This is the minimum to start, but I think it helps.

//aqui vai sempre ser a hora atual
var startDate = new Date();
//como exemplo vou definir a data de fim com base na data atual
var endDate = new Date();
endDate.setDate(endDate.getDate()+5);

//aqui é a diferenca entre as datas, basicamente é com isso que voce calcula o tempo restante
var dateDiff;
var days, hours, minutes, seconds;
var $day = $('#dias');
var $hour = $('#horas');
var $minute = $('#minutos');
var $second = $('#segundos');
var $debug = $('#debug');
var timer;

function update(){
	dateDiff = endDate - startDate;
  dateDiff = dateDiff / 1000;
  
	seconds = Math.floor((dateDiff % 60));
  
  dateDiff = dateDiff / 60;
  minutes = Math.floor((dateDiff % 60));
	
  dateDiff = dateDiff / 60;
  hours = Math.floor((dateDiff%24));
  
	days = Math.floor(dateDiff/24);
  
  $day.text(days);
  $hour.text(hours);
  $minute.text(minutes);
  $second.text(seconds);
  
  startDate.setSeconds(startDate.getSeconds()+1);
}
update();
timer = setInterval(update, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><divid="dias"></div>
<div id="horas"></div>
<div id="minutos"></div>
<div id="segundos"></div>
<div id="debug"></div>
    
16.08.2016 / 14:37