Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

113
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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()

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!