1

I did something like

setInterval(function() {
   console.log("!");
   }, 1000 * 60 * 60);

I want to run console.log every hour but the code doesn't work like what I want.

Let's say that I run the code at 1:30, then It would run console.log at 2:30. but What I want to do is run the code every hour. like 1:00, 2:00, 3:00.

Is there any way to do this? Thank you!

yolohoam
  • 31
  • 2
  • 6

1 Answers1

1

This should do it:

let millisPerHour = 60 * 60 * 1000; // use 5 * 1000 (every 5 seconds) for testing
let millisPastTheHour = Date.now() % millisPerHour;
let millisToTheHour = millisPerHour - millisPastTheHour;

let fn = function() {
  console.log("Running at " + new Date());
}

setTimeout(function() {
  fn();
  
  setInterval(function() {
    fn();
  }, millisPerHour);
}, millisToTheHour);

I'm using a combination of setTimeout() and setInterval(). First I calculate the number of milliseconds until the next hour (millisToTheHour), then I use a timeout to execute the function and start an interval that will keep executing it every hour.

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156