0

I was watching "10 Javascript projects in 10 hours on Youtube", and there is an important part of the code I'm struggling to understand, on the first project which is a countdown timer from Sept 2020, to New Years 2021.

Here's the code:

const newYears = '1 jan 2021';
function countdown (){
 
 const newYearsDate = new Date (newYears);
 const currentDate = new Date ();

 const totalSeconds = (newYearsDate - currentDate)/1000;
 const days = Math.floor(totalSeconds/3600/24);
 const hours = Math.floor(totalSeconds/3600)%24;
 const mins = Math.floor(totalSeconds/60)%60;
 const seconds = Math.floor(totalSconds)%60;

 daysE1.innerHTML = days;
 hoursE1.innerHTML = hours;
 minsE1.innerHTML = mins;
 secondsE1.innerHTML = seconds;
}

I understand the first and last blocks of lines inside the function, but as for the one in the middle, I'm completely lost. This is basic Math so I understand the calculations I just don't understand why:

  1. in order to get the seconds with divide newYearsDate and currentDate's difference by 1000.
  2. in order to get the remaining days, we divide the total of seconds by 3600 and then divide the result by 24.
  3. Probably the most confusing thing for me, why are using remainders ? I know what remainders are but I don't understand their meaning in this case ?

In conclusion I just need someone to explain to me the reasoning behind every line from "const totalSeconds" to "const seconds". I understand what** we're doing, but not how we're doing it :/.

Thank you so much, in advance !!

Hope you're having a lovely day !

Heny
  • 13
  • 1
  • If you subtract one javascript date from another, it gives you the difference between them in milliseconds. to know more about this you can visit this https://en.wikipedia.org/wiki/Unix_time – Risalat Zaman May 25 '21 at 10:50

1 Answers1

1

in order to get the seconds with divide newYearsDate and currentDate's difference by 1000.

See https://stackoverflow.com/a/41960/1468366 and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#examples for the difference in ms. Divide by 1000 to get total difference in seconds.

in order to get the remaining days, we divide the total of seconds by 3600 and then divide the result by 24.

There are 3600 seconds in an hour, and 24 hours in a day. Duh.

Probably the most confusing thing for me, why are using remainders ? I know what remainders are but I don't understand their meaning in this case ?

Divide seconds by 60 and round down (floor) to get full minutes. Use % 60 to get seconds in excess of those full minutes, which are the ones you want to display as actual seconds. Same idea for minutes in excess of full hours, and for hours in excess of full days.

MvG
  • 57,380
  • 22
  • 148
  • 276