Home > Back-end >  how to create a countdown that repeats every 48 or 72 hours
how to create a countdown that repeats every 48 or 72 hours

Time:12-23

I'm trying to create a countdown that repeats every 24, 48 or 72 hours at midnight without moment.js

For example (example for 48 hours):

10-12-22 00:00 -> start countdown -> 47:59:59

11-12-22 22:30 -> countdown = 1:30:00

12-12-22 00:00 -> the countdown restart -> 47:59:59

I try solution only for 24 hours

I try this:

setInterval(function time() {
  var d = new Date();
  var hours = 24 - d.getHours();
  var min = 60 - d.getMinutes();
  if ((min   '').length == 1) {
    min = '0'   min;
  }
  var sec = 60 - d.getSeconds();
  if ((sec   '').length == 1) {
    sec = '0'   sec;
  },
1000);

CodePudding user response:

There are a huge number of questions and answers already about timers and countdowns. Pick one.

The only point of interest here is that it should to restart when the remainder gets to zero, e.g.:

// Counts down period milliseconds, then restarts
function timer(period) {
  let start = new Date();
  let z = n => ('0' n).slice(-2); 
  let zz = n => ('00' n).slice(-3); 
  let f = ms => {
    let day = (ms / 8.64e7) | 0;
    let hr = (ms % 8.64e7) / 3.6e6 | 0;
    let min = (ms % 3.6e6) / 6e4 | 0;
    let sec = (ms % 6e4) /1e3 | 0;
    let mil = (ms % 1e3);
    return `${day} days, ${z(hr)}:${z(min)}:${z(sec)}.${zz(mil)}`;
  }
  setInterval(() => {
    console.log(f(period - (Date.now() - start) % period));
  }, 1000);
}

timer(1000*5);

Format the output however you want, maybe floor the seconds and ditch the milliseconds.

BTW, setInterval is not a good way to run a timer. Use successive calls to setTimelout with the lag set to about 10ms longer than the time to the next full second, minute or whatever. That way it won't be seen to miss a second (which happens with setInteval because it may slowly drift, as can be seen in the ms part of the above, there is always at least 1e3 ms between logs, usually more and sometimes a lot more, depending on how busy the system is with other tasks).

CodePudding user response:

I don't really get the question but perhaps try setInterval?


//this will log to console after 2 days
setInterval(() => {
    console.log("Ding Dong");
    },
2*24*60*60*1000);

  • Related