skip to Main Content

I have a JavaScript function of chrome extension that I need to run at exact 5-minute intervals, synchronized with the current time. For example, it should run at 5:00, 5:05, 5:10, and so on, regardless of when the script starts running.

Here is the approach I am trying to implement:

Calculate the delay until the next 5-minute mark.
Use setTimeout to call the function at the next 5-minute mark.
Set up a setInterval to call the function every 5 minutes after the initial timeout.
Here is a simplified version of the code to demonstrate the issue:

function myFunction() {
    console.log("Function executed at:", new Date().toLocaleTimeString());
}

function checkTimeAndRunMainFunction() {
    let now = new Date();
    let minutes = now.getMinutes();
    let seconds = now.getSeconds();

    if (seconds === 0 && minutes % 5 === 0) {
        // Run the main function immediately
        myFunction();
    }
}

function calculateDelayToNextFiveMinuteMark() {
    let now = new Date();
    let millisecondsUntilNextFiveMinuteMark = (5 - (now.getMinutes() % 5)) * 60 * 1000 - now.getSeconds() * 1000 - now.getMilliseconds();
    return millisecondsUntilNextFiveMinuteMark;
}

// Set an initial timeout to synchronize with the next 5-minute mark
setTimeout(function() {
    checkTimeAndRunMainFunction();
    // Set an interval to check the time every 5 minutes after the initial call
    setInterval(checkTimeAndRunMainFunction, 5 * 60 * 1000);
}, calculateDelayToNextFiveMinuteMark());

The problem I am facing is that setInterval(checkTimeAndRunMainFunction, 1000); counts every second from the moment the user runs the code, and it does not synchronize with the actual clock’s seconds, resulting in the condition if (seconds === 0 && minutes % 5 === 0) not being met precisely.

How can I ensure that my function runs exactly at the 5-minute marks (e.g., 5:00, 5:05, 5:10) regardless of when the script starts running?

2

Answers


  1. Here simple script that runs every 5 minute and adjust next start time on every run

    (function loop () {
      let date = new Date();
      let sec = date.getSeconds();
      let mssec = date.getMilliseconds();
       setTimeout(async () => { 
         console.log(date)
         
         loop();
         // your code here
       }, 300000 - sec * 1000 - mssec);
    })();
    Login or Signup to reply.
  2. Here is a safer script. It will execute every time the interval gets a 5 minute mark and then it will move the entry to the end of the array. That means that there is room for some wobble

    You can add checkTimeAndRunMainFunction() before the setInterval to run it immediately if the user starts it at an exact 5 minute time

    const myFunction = () => {
      console.log("Function executed at:", new Date().toLocaleTimeString());
    }
    
    const getNearestFiveMinuteMark = () => {
      const now = new Date();
      const minutes = now.getMinutes();
      return Math.ceil(minutes / 5) * 5;
    }
    
    const initializeFiveMinuteArray = () => {
      const nearestFiveMinuteMark = getNearestFiveMinuteMark();
      const intervals = [];
      for (let i = 0; i < 12; i++) { // 12 entries for every 5 minutes in an hour
        intervals.push((nearestFiveMinuteMark + i * 5) % 60);
      }
      return intervals;
    }
    
    const checkTimeAndRunMainFunction = () => {
      const now = new Date();
      const currentMinute = now.getMinutes();
    
      if (currentMinute === fiveMinuteIntervals[0]) {
        // Run the main function and move the entry to the end
        myFunction();
        const executedEntry = fiveMinuteIntervals.shift();
        fiveMinuteIntervals.push(executedEntry);
      }
      time.textContent = `next run will be at :${String(fiveMinuteIntervals[0]).padStart(2,'0')}`;
    }
    
    const fiveMinuteIntervals = initializeFiveMinuteArray();
    console.log("Initial 5-minute intervals array:", fiveMinuteIntervals);
    
    // Set an interval to check the time every second
    setInterval(checkTimeAndRunMainFunction, 1000);
    <span id="time"></span>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search