Search code examples
javascriptdatetimersetintervalclearinterval

setInterval function every day, but pass a random integer to another function. So that function fires once every day at a random time


I feel like I am close with this. I want to fire a function at a random point every 24 hours (for testing purposes I am just trying to update every 10 seconds).

Here is my javascript:

let now = new Date();
let rndInt = Math.floor(Math.random() * 1000 * 10);

setInterval(function() {
  now = new Date();
  rndInt = Math.floor(Math.random() * 1000 * 10);
}, 10 * 1000); // 10 * 1000 milsec

const customTimerFunction = () =>
  setInterval(function() {
    console.log('random int function', now, rndInt)
  }, rndInt);
  
clearInterval(customTimerFunction);

customTimerFunction();

As I understand it the anonymous setInterval function runs every 10 seconds and updates the rndInt variable. This is used by the customTimerFunction, but is cleared after each iteration of the function call. When it runs again it should have a new rndInt value passed to it.

It seems the rndInt value is being updated but the console seems to be logging every 10 seconds, so I assume this is being updated by the regular anonymous setInterval function.

I have made a jsfiddle.

What I want to try and avoid is the custom function running twice in one day.

Any pointers?

EDIT

This will be used in a nodejs application, so I can look at using some cron library, although I am not super familiar with cron syntax, but happy to explore that if it is an easy option to integrate.


Solution

  • If you want it to run at a random point during every 24 hour interval I would have an interval for 24 hours which schedules the function to run at some point in the next 24 hour, i.e.

    const myFunction = function() {
      console.log(`I ran at ${new Date().toISOString()}`);
    };
    
    const INTERVAL_PERIOD = 1000 * 60 * 60 * 24;
    
    const intervalFunction = function() {
      const nextRunIn = Math.floor(Math.random() * INTERVAL_PERIOD);
      console.log(`The time is ${new Date().toISOString()}, scheduling run at ${new Date(Date.now() + nextRunIn).toISOString()}`);
      setTimeout(myFunction, nextRunIn);
    };
    
    setInterval(intervalFunction, INTERVAL_PERIOD);
    intervalFunction();