How do I make a stopwatch down to a date?

Posted on

Question :

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.


Answer :

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


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=""></script><divid="countdown"></div>


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();

//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);
timer = setInterval(update, 1000);
<script src=""></script><divid="dias"></div>
<div id="horas"></div>
<div id="minutos"></div>
<div id="segundos"></div>
<div id="debug"></div>


Leave a Reply

Your email address will not be published. Required fields are marked *