Search code examples
javascriptsetintervaldayjs

Checking setInterval every 5 minutes on the 0 second


const secondsInterval = () => {
  const date = getNow();
  if (dayjs(date).minute() % 5 !== 0 && dayjs(date).second() !== 0) {
    console.log("return...");
    return;
  }
  console.log("checking...");
  ...
};
// Check every second, if we're at the 5-minute interval check.
setInterval(secondsInterval, 1000);

This seems to get stuck. It's "checking" on every second of each 5 minute mark. What am I doing wrong? Thanks in advance.

Goal: To "check" every minute and 00 seconds: :00:00, :05:00, :10:00, , :15:00, etc Thanks again.


Solution

  • You should find out what's the time to your next rounded 5 min. like this:

    const FIVE_MIN = 1000 * 60 * 5;
    
    function waitAndDoSomething() {
      const msToNextRounded5Min = FIVE_MIN - (Date.now() % FIVE_MIN);
      console.log(`Waiting ${msToNextRounded5Min}ms. to next rounded 5Min.`);
    
      setTimeout(() => {
        console.log('It is now rounded 5 min');
        waitAndDoSomething();
      }, msToNextRounded5Min);
    }
    
    waitAndDoSomething();