willmahoney
willmahoney

Reputation: 451

How to set setInterval time depending on time of day

I have to run a group of functions every so often, during the day I have to run them every 2 minutes, in the evening they need to run every 3 minutes and at night they need to run every 5 minutes. Right now I'm running them like this, with every function running every 2 minutes at all times of the day.

const function1 = () => DO_SOMETHING

const function2 = () => DO_SOMETHING_ELSE

const function3 = () => DO_SOMETHING_ANTOTHER_THING

setInterval(() => {
    function1()
}, 1000 * 60 * 2)

setInterval(() => {
    function2()
}, 1000 * 60 * 2)

setInterval(() => {
    function3()
}, 1000 * 60 * 2)

Does anyone know how I can set this up so that the time variable changes depening on what time of day it is?

Upvotes: 0

Views: 749

Answers (1)

DBS
DBS

Reputation: 9984

This can be done by using a setTimeout that triggers itself, instead of a setInterval.

Overview:

  • Set up a function that builds your timeout with the correct duration for the current time using Date().getHours() to find the time.
  • Call this builder function on load.
  • Set up a result function, and call the builder function inside there as well.
  • Add whatever the desired result is to the result function.

Example:

(You can change the definition of "evening" and "night" using the two if statements)

// This is required if you ever want to use clearTimeout()
let timeoutRefernce = null

// Run the desired code after X amount of time
const result = () => {
  // Start a new iteration of the timer
  newTimeout()
  // Run your resulting code
  // e.g. Call function1, function2 and function3
  console.log('Result')
}

const newTimeout = () => {
  const time = new Date().getHours()
  let minutes = 2
  // Is it evening? (Between 5pm and 10pm)
  if (time > 17 && time < 22) {
    minutes = 3
  }
  // Is it night? (Between 10pm and 6am)
  if (time > 22 || time < 6) {
    minutes = 5
  }
  // Create a new timeout with the relevant duration
  timeoutRefernce = setTimeout(result, 1000 * 60 * minutes)
  console.log(`Hour: ${time}, New timeout created with duration ${minutes} minutes`)
}

// Run the first timeout on load
newTimeout()

Upvotes: 3

Related Questions