Skip to content

Instantly share code, notes, and snippets.

@farhad-taran
Last active January 7, 2024 13:27
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save farhad-taran/f487a07c16fd53ee08a12a90cdaea082 to your computer and use it in GitHub Desktop.
Save farhad-taran/f487a07c16fd53ee08a12a90cdaea082 to your computer and use it in GitHub Desktop.
How to run a Javascript function at a specific time of day

some scenarios require us to run a piece of code at a specific time of day, the following method allows us to do this:

function runAtSpecificTimeOfDay(hour, minutes, func)
{
  const twentyFourHours = 86400000;
  const now = new Date();
  let eta_ms = new Date(now.getFullYear(), now.getMonth(), now.getDate(), hour, minutes, 0, 0).getTime() - now;
  if (eta_ms < 0)
  {
    eta_ms += twentyFourHours;
  }
  setTimeout(function() {
    //run once
    func();
    // run every 24 hours from now on
    setInterval(func, twentyFourHours);
  }, eta_ms);
}

and this is how you log out the current date at 6:01 every day:

runAtSpecificTimeOfDay(6,1,() => { console.log(new Date())});
@quanglong292
Copy link

thank you!

@Trungfc
Copy link

Trungfc commented Apr 19, 2023

Thank you very much!

@MichelBeaubien
Copy link

Thank you!!!!

@andreimaier
Copy link

Great! Thank you!

@Dev-SK01
Copy link

Dev-SK01 commented Jan 7, 2024

I have a question to run this code our environment or browser needs to run is that correct or not

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment