'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 1:[1]

If all you care about is executing some code every 5 mins, then don't have it execute every second needlessly, only to return out. Just have it run every 5 mins (300000 MS) and have it do what you need to do and remove all the checking for 5 minute mark code out its unnecessary.

const secondsInterval = () => {

  // -------------------- Remove ----------------
  //const date = getNow();
  //if (dayjs(date).minute() % 5 !== 0 && dayjs(date).second() !== 0) {
  //  console.log("return...");
  //  return;
  //}
  // -------------------- Remove ----------------

  console.log("checking...");
  ...
};
// Check every 5 mins
setInterval(secondsInterval, 300000);

Solution 2:[2]

Your logic for the if is screwy. Here I reversed it so the if takes care of "do the thing" and the else returns.

const secondsInterval = () => {
  const date = dayjs(new Date());
  if (dayjs(date).minute() % 5 == 0 && dayjs(date).second() == 0) {
    console.log("checking...");
  } else {
    console.log("returning...");
    return;
  }
  //...
};
// Check every second, if we're at the 5-minute interval check.
setInterval(secondsInterval, 1000);
<script src="https://unpkg.com/[email protected]/dayjs.min.js"></script>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 maraaaaaaaa
Solution 2 James