DEV Community

Discussion on: JavaScript Functions That Will Make Your Life Much Easier [Updatable].

Collapse
 
krimfandango profile image
Kareem Kamal • Edited

Hello, nice list!

runEvery function is broken, it runs a script every x milliseconds if hour is after the given hour and minute is after the given minute, so given this input:

runEvery(() => console.log('ran'), 12, 30, 300000)
Enter fullscreen mode Exit fullscreen mode

and the time now is 3:17 PM it will try running at 8:17 PM but now.getMinutes() >= mins will return false and the function will not execute, and every 5 hours it will always return false
But if you set minutes to 0 or someone starts the application after the provided minute it will execute every interval after the given time.

If the goal is to make a function that runs every day at a certain time, you need to get the time to the next occurrence and start the interval then, something like this:

function runEverydayAt(callback, hour, minute) {
  // first we need to get the time until the next hour:minute
  const now = new Date()
  // to check if the next time happens today check how many minutes
  // passed in the day and compare them with the input
  const nowInMinutes = (now.getHours() * 60) + now.getMinutes()
  const inputTimeInMinutes = (hour * 60) + minute
  const isNextTimeToday = nowInMinutes < inputTimeInMinutes

  // create a new date for the comparison
  const firstTime = new Date()
  // and set its time to the input's time
  firstTime.setHours(hour, minute, 0)

  if (!isNextTimeToday) {
    // if next time is today then add a day
    firstTime.setDate(now.getDate() + 1)
  }

  const timeUntilNextOccurrence = firstTime.getTime() - now.getTime()

  // finally set a timeout to start the first call
  // on time then every other call every 24 hours
  setTimeout(() => {
    // setInterval will start kicking in after 24 hours
    // therefore we need to invoke the first callback here
    callback()
    setInterval(callback, 1000 * 60 * 60 * 24)
  }, timeUntilNextOccurrence)
}

// to check you can try invoking it with a time that's coming soon
runEverydayAt(() => console.log('I ran!'), 10, 43)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
youssefzidan profile image
Youssef Zidan

Great!
Thanks for your feedback!
I'll check my code again and get back to you.

Collapse
 
youssefzidan profile image
Youssef Zidan • Edited

Hello!
I tried to run your function but it doesn't seem to be working.

Thread Thread
 
krimfandango profile image
Kareem Kamal

Hey Youssif, I've just tried running the code in the console and it seems to be working.
You just need to set the time to be coming up in a minute or two so that you wouldn't wait for long for the next occurrence

Image