Do a Timer by Javascript

Daniel WANG
Front-End Record
Published in
1 min readJun 20, 2018

--

Here is the code:

var endDate = new Date(“2019–06–20T24:00:00.00”);timer = setInterval(function() { //timer call func every 1000ms( 1s)

timeBetweenDates(endDate);
}, 1000);function timeBetweenDates(endDate) { //calculate how many time left
var nowDate = new Date();
var difference = endDate — nowDate;if (difference <= 0) {// Timer done
clearInterval(timer);
} else {var left;var days = Math.floor(difference / (1000 *60 *60 *24));
left = difference % (1000 *60 *60 *24);
var hours = Math.floor( left / (1000 *60 *60));
left = left % (1000 *60 *60);
var minutes = Math.floor( left / (1000 *60 ));
left = left % (1000 *60);
var seconds = Math.floor( left / 1000 );
console.log(days+”days “+ hours+ “:” + minutes +”:” + seconds);
}
}// end of timeBetweenDates
  1. Timer will call the function to check the interval between now time & end time and print as the format time.

2. var difference is millisecond between now time & end time.

3. add string “0” if hours or minutes or seconds < 10

--

--