Home > Enterprise >  javascript better countdown
javascript better countdown

Time:10-19

hello i have a javascript countdown that counts down from seconds and shows formatted how many hours minutes and seconds are left so far so good. my question would be how could i make this countdown count down intelligently so let's say i have 2 hours so 7200 seconds as a value and i want this to be counted down. currently it shows how many hours and minutes are left so 01:119:59 but i would like to have it displayed more logically so 01:59:59 how can i implement this?

My Code:

     const secondRatios = {
     minute: 60,
     hour: 3600,
     };

const formatSeconds = (s) => {
const hours = Math.floor(s / secondRatios.hour)
.toString()
.padStart(2, '0');
const minutes = Math.floor(s / secondRatios.minute)
.toString()
.padStart(2, '0');
const seconds = (s % 60).toString().padStart(2, '0');
return `${hours}:${minutes}:${seconds}`;
};

CodePudding user response:

You have to subtract "s" after each operation, something like this:

const formatSeconds = (s) => {
  const hours = Math.floor(s / 3600);
  s -= hours * 3600;
  const minutes =  Math.floor(s / 60);
  s -= minutes * 60;
  return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
};

console.log(formatSeconds(7200));

  • Related